I have this problem which made my scratch my head:
Is there a way to use regular expression to test a 4 characters string with at least a letter “J”? This is what I come with:
^(j...|.j..|..j.|...j)$
Yes, I admit it’s ugly, and it’s would be mad if the question changes 4 character to 10 character, or change “at least one j” to “with at least one j AND one k”
What the more elegant and compatible way to write an RegEx for this?
Additional question:
- If there is no easy answer, academically, what’s the limit of RegExp? Why it can’t solve simple problem like this?
- Any DSL suitable for these kinds of tasks?
- What’s the best RegEx for “10 character string with at least one j and one k” ?
If your regex engine supports lookahead (most do), you can use
The lookahead
(?=.*j)asserts that there is ajsomewhere in the string without actually consuming any of the string for the match. The following.{4}will then match a four-character string.The
^and$anchors make sure that the string is matched in its entirety.If you want to add more constraints, simply add another lookahead:
matches if at least one
jand onekare present in a string that’s exactly 10 characters long. Etc…