Skip to content
Advertisement

Regex return true if even a substring follows the pattern

I was just practicing regex and found something intriguing

for a string

"world9 a9$ b6$" my regular expression "^(?=.*[\d])(?=\S+\$).{2,}$"

will return false as there is a space in between before the look ahead finds the $ sign with at least one digit and non space character.

As a whole the string doesn’t matches the pattern.

What should be the regular expression if I want to return true even if a substring follows a pattern? as in this one a9$ and b6$ both follow the regular expression.

Advertisement

Answer

You can use

^(?=D*d)(?=.*S$).{2,}$

See the regex demo. As The fourth bird mentions, since S$ matches two chars, you may simply move the pattern to the consuming part, and use ^(?=D*d).*S$.*$, see this regex demo.

Details

  • ^ – start of string (implicit if used in .matches())
  • (?=D*d) – a positive lookahead that requires zero or more non-digit chars followed with a digit char immediately to the right of the current location
  • (?=.*S$) – a positive lookahead that requires zero or more chars other than line break chars, as many as possible, followed with a non-whitespace char and a $ char immediately to the right of the current location
  • .{2,} – any two or more chars other than line break chars, as many as possible
  • $ – end of string (implicit if used in .matches())
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement