How to ignore whitespace in a regular expression subject string?

后端 未结 6 613
梦毁少年i
梦毁少年i 2020-11-27 03:33

Is there a simple way to ignore the white space in a target string when searching for matches using a regular expression pattern? For example, if my search is for \"cats\",

6条回答
  •  难免孤独
    2020-11-27 04:06

    Addressing Steven's comment to Sam Dufel's answer

    Thanks, sounds like that's the way to go. But I just realized that I only want the optional whitespace characters if they follow a newline. So for example, "c\n ats" or "ca\n ts" should match. But wouldn't want "c ats" to match if there is no newline. Any ideas on how that might be done?

    This should do the trick:

    /c(?:\n\s*)?a(?:\n\s*)?t(?:\n\s*)?s/
    

    See this page for all the different variations of 'cats' that this matches.

    You can also solve this using conditionals, but they are not supported in the javascript flavor of regex.

提交回复
热议问题