how to use dotall flag for regex.exec()

后端 未结 4 874
我寻月下人不归
我寻月下人不归 2020-11-30 11:34

i want get to string in a multiline string that content any specific character and i want get to between two specific staring.

i used this regex and this work but if

4条回答
  •  孤街浪徒
    2020-11-30 11:44

    In 2018, with the ECMA2018 standard implemented in some browsers for the time being, JS regex now supports s DOTALL modifier:

    Browser support

    console.log("foo\r\nbar".match(/.+/s)) // => "foo\r\nbar"

    Actually, JS native match-all-characters regex construct is

    [^]
    

    It means match any character that is not nothing. Other regex flavors would produce a warning or an exception due to an incomplete character class (demo), though it will be totally valid for JavaScript (demo).

    The truth is, the [^] is not portable, and thus is not recommendable unless you want your code to run on JS only.

    regex = /--Head([^]*)--\/Head/
    

    To have the same pattern matching any characters in JS and, say, Java, you need to use a workaround illustrated in the other answers: use a character class with two opposite shorthand character classes when portability is key: [\w\W], [\d\D], [\s\S] (most commonly used).

    NOTE that [^] is shorter.

提交回复
热议问题