Home > OS >  Ignoring \n in regex even if its tied to the word you are looking for
Ignoring \n in regex even if its tied to the word you are looking for

Time:12-01

Let's say I have this text:

"""xsdsdsds\ncat xsdhidhf"""

and my regex is:

val myRegex = "\b(?i)cat\b"

This doesn't recognize that the text above has the word cat in it because its tied to the \n character.

How can I change the regex to find a word as a whole (with spaces from both sides) but ignore the \n?

CodePudding user response:

You can use

val myRegex = """(?i)(?<=\b|\\n)cat\b"""

Details:

  • (?i) - case insensitive matching on
  • (?<=\b|\\n) - either a word boundary or a \n text must appear immediately on the left
  • cat - a string cat
  • \b - a word boundary.

See the regex demo.

  • Related