[英]Multi-line regular expression is not working right
我正在尝试使用正则表达式来定位时间并向其中添加文本。 但是当输入字符串有换行符时,我的正则表达式有问题。 如果我删除中断并测试该表达式,它将起作用。
另外,找到目标时间后,如何在目标时间前后添加文字?
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);
正如其他人指出的那样,您需要首先修复多行字符串。
完成此操作后,您可以使用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);
您可以在小提琴中尝试一下。
有关replace
方法的更多信息,请查看MDN的参考页 。
您为str分配值的方式不正确。 您的浏览器必须阻止了您的脚本,因此从未进行过解析。
您可以按如下所示用\\ 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.";
您可以检查该小提琴以了解其工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.