简体   繁体   English

多行正则表达式无法正常工作

[英]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: 完成此操作后,您可以使用replace方法而不是match方法在匹配时间前后添加文本:

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 . 有关replace方法的更多信息,请查看MDN的参考页

The way you assign the value for str is incorrect. 您为str分配值的方式不正确。 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, 您可以按如下所示用\\ r \\ n替换换行符,

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. 您可以检查该小提琴以了解其工作原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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