21

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 content have any character (\r \n \t) not work and get null value.

This Wotked
    var regex = new RegExp("\-{2}Head(.*)-{2}\/\Head");      
    var content = "--Head any Code and String --/Head";
    var match = regex.exec(content);

This Not Worked

var regex = new RegExp("\-{2}Head(.*)-{2}\/\Head");      
var content = "--Head \n any Code \n and String --/Head";
var match = regex.exec(content);

i found a regexer(http://www.regexr.com/v1/) and know i should use Dotall for multiline string but i cant use dotall for regex.exec

thanks.

HapyUser
  • 264
  • 3
  • 13

4 Answers4

35

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.

Klesun
  • 12,280
  • 5
  • 59
  • 52
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
28

javascript doesn't support s (dotall) modifier. The only workaround is to use a "catch all" class, like [\s\S] instead of a dot:

regex = new RegExp("\-{2}Head([\\s\\S]*)-{2}\/\Head")

Also note that your expression can be written more concisely using a literal:

regex = /--Head([\s\S]*)--\/Head/
gog
  • 10,367
  • 2
  • 24
  • 38
2

Use catch all character class [\s\S] which means space or non space

var regex = new RegExp("\-{2}Head([\s\S]*)-{2}\/\Head","m");      
var content = "--Head \n any Code \n and String --/Head";
var match = regex.exec(content);
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
1

You are looking for the s modifier, also known as the dotall modifier which forces the dot . to also match newlines. The dotall modifier does not exist in . The workaround is replacing the dot . with...

[\S\s]*

Your regular expression would look like this.

var regex = /-{2}Head([\S\s]*)-{2}\/Head/
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • 1
    [This answer is now obsolete](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll). – Dan Dascalescu Feb 10 '21 at 22:26