Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore newline in regexp?

Tags:

javascript

How to ignore newline in regexp in Javascript ?

for example:

 data = "\
    <test>11\n
    1</test>\n\
    #EXTM3U\n\
 "
 var reg = new RegExp( "\<" + "test" + "\>(.*?)\<\/" + "test" + "\>" )
 var match = data.match(reg)
 console.log(match[1])

result: undefined

like image 351
Bdfy Avatar asked May 27 '13 10:05

Bdfy


People also ask

How do you escape a new line in regex?

In pattern matching, the symbols “^” and “$” match the beginning and end of the full file, not the beginning and end of a line. If you want to indicate a line break when you construct your RegEx, use the sequence “\r\n”.

What is \r and \n in regex?

Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

How do you remove a line break in a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.

Does regex dot match newline?

By default in most regex engines, . doesn't match newline characters, so the matching stops at the end of each logical line. If you want . to match really everything, including newlines, you need to enable "dot-matches-all" mode in your regex engine of choice (for example, add re. DOTALL flag in Python, or /s in PCRE.


2 Answers

In JavaScript, there is no flag to tell to RegExp() that . should match newlines. So, you need to use a workaround e.g. [\s\S].

Your RegExp would then look like this:

var reg = new RegExp( "\<" + "test" + "\>([\s\S]*?)\<\/" + "test" + "\>" );
like image 57
t.niese Avatar answered Oct 05 '22 23:10

t.niese


You are missing a JS newline character \ at the end of line 2.

Also, change regexp to:

 var data = "\
    <test>11\n\
    1</test>\n\
    #EXTM3U\n\
 ";
 var reg = new RegExp(/<test>(.|\s)*<\/test>/);
 var match = data.match(reg);
 console.log(match[0]);

http://jsfiddle.net/samliew/DPc2E/

like image 30
Samuel Liew Avatar answered Oct 06 '22 00:10

Samuel Liew