简体   繁体   中英

Multi-line regular expression is not working right

I am trying to use a regular expression to target times and add text to them. But my regular expression has a problem when the input string has line breaks. If I remove the breaks and test the expression, it works.

Also, after I have found targeted times, how do I add text in front of and behind them?

var str = "00:00:01.120
In this lesson, we will learn how to determine the equation of a line, using the available information.

00:00:08.040
Let's look at the first example. Determine the equation of the line, that passes through the points (2, 5), and with the slope of 2. 

00:00:19.000
To begin, we should know that the equation of a line can be written in the form of y = mx + b, where m is the slope, and b is the y-intercept.";


    var patt1 = /(\d\d.\d\d.\d\d.\d\d\d)/gm;
    var result = str.match(patt1);

As others have noted, you need to first fix your multi-line string.

With this done, you can use the replace method rather than the match method to add text before and after matched times:

var str = "00:00:01.120\n\
In this lesson, we will learn how to determine the equation of a line, using the available information.\n\
\n\
00:00:08.040\n\
Let's look at the first example. Determine the equation of the line, that passes through the points (2, 5), and\ with the slope of 2.\n\
\n\
00:00:19.000\n\
To begin, we should know that the equation of a line can be written in the form of y = mx + b, where m is the\ slope, and b is the y-intercept.";


var patt1 = /(\d\d.\d\d.\d\d.\d\d\d)/gm;
//var result = str.match(patt1);
var result = str.replace(patt1, "<some text>\$1<some other text>");
alert(result);

You can try this in a fiddle .

For more information on the replace method, check out MDN's reference page .

The way you assign the value for str is incorrect. Your browser must have blocked your script and hence the parsing had never taken place.

You may replace the line breaks with \\r\\n as follows,

var str = "00:00:01.120\r\nIn this lesson, we will learn how to determine the equation of a line, using the available information.\r\n00:00:08.040\r\nLet's look at the first example. Determine the equation of the line, that passes through the points (2, 5), and with the slope of 2.\r\n00:00:19.000\r\nTo begin, we should know that the equation of a line can be written in the form of y = mx + b, where m is the slope, and b is the y-intercept.";

You can check this fiddle to see how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM