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 your regex engine supports lookahead (most do), you can use
^(?=.*j).{4}$
The lookahead (?=.*j)
asserts that there is a j
somewhere 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:
^(?=.*j)(?=.*k).{10}$
matches if at least one j
and one k
are present in a string that's exactly 10 characters long. Etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With