0

I have a question about restricting the value entered in some input field. I would like to input this :

9digits-whatever, for example 101010101-Teststring.

I have come up with this regex as a solution, but it does not seem to be correct:

^\d{9}\-[a-zA-Z0-9_]*$

Any ideas on this one?

Thank you.

2
  • 1
    Just use /^\d{9}-.+$/ Commented Jul 11, 2014 at 14:49
  • Remember that /[a-zA-Z0-9_]/ is exactly /\w/ Commented Jul 11, 2014 at 17:20

2 Answers 2

2

The below regex would match 9 digits follwed by - and any number of characters.,

^\d{9}-.*$

If you want a minimum of one character followed by -, then try the below regex.

^\d{9}-.+$

Explanation:

  • ^ Asserts that we are at the beginning of the line.
  • \d{9} Exactly 9 digits.
  • \- Literal - symbol.
  • .* Matches any character zero or more times.
  • $ End of the line.
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, Avinash Raj, that did it!
IS there any need to escape hyphen?
@Braj but both will work. And op wants to match any character after -.
That's correct but there is no need to escape hyphen. Is it?
Do you know why $ doesn't work as negative [^$]* look up but works if added in the end.
1
  • There is no need to escape hyphen -.
  • Use \w that include [a-zA-Z0-9_]

Try below regex if there is only [a-zA-Z0-9_] after 9 digits and hyphen.

^\d{9}-\w*$

Online demo

2 Comments

OP's $ in this case matches the end of the string, not a literal '$'
@RevanProdigalKnight sorry that part is deleted but $ works in the end but not as part of negative character set.

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.