Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Four letter word with at least a "j", elegant and most compatible regex solution?

Tags:

regex

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:

  1. If there is no easy answer, academically, what's the limit of RegExp? Why it can't solve simple problem like this?
  2. Any DSL suitable for these kinds of tasks?
  3. What's the best RegEx for "10 character string with at least one j and one k" ?
like image 312
est Avatar asked Dec 06 '22 00:12

est


1 Answers

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 kare present in a string that's exactly 10 characters long. Etc...

like image 199
Tim Pietzcker Avatar answered Apr 27 '23 07:04

Tim Pietzcker