1

I have 2 regexps in ruby. The first regex is for letters and digits something like:

letter_digits = /^([0-9]*[a-zA-Z][a-zA-Z0-9]*)$/

With this regex if I write only digits 564521 does not match!

However I have this regex for only digits:

only_digits = /^([0-9])*$/

But with this regex if I write s45xo does not match!

I need only 1 regex valid for both letters/digits and digits.

2 Answers 2

5

Try: letter_digits = /^[0-9a-zA-Z]*$/

Your first regexp /^([0-9]*[a-zA-Z][a-zA-Z0-9]*)$/ says that there should be digits (0 or more), then letter (1), then digits or letters (0 or more).

My advise is to read something about regexp, for example tutorial

Sign up to request clarification or add additional context in comments.

2 Comments

No because "this shouldn't\nmatch" =~ /^[0-9a-zA-Z]*$/
That string shouldn't match the regex.
2

The simplest regex is:

/\A[a-z\d]*\Z/i

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.