簡體   English   中英

多行正則表達式無法正常工作

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM