我已经在线阅读了如何在字符串之后找到字符串的第一个匹配项,但是我试图在字符串之前找到它。
我最近才开始使用正则表达式,所以这可能是一个非常简单的问题。
示例文本:
03:47:06 This is line 1
03:47:07 This is line 2
03:47:08 This is line 3
03:47:09 This is line 4
This is line 5
03:47:10 This is line 6
03:47:11 This is line 7
This is line 8
我希望能够使变量返回特定字符串之前的第一个时间戳。
例如,第4行的时间戳,我需要一个变量以返回03:47:09
我有正则表达式:
/\d\d:\d\d:\d\d/
我大概可以通过遍历寻找正则表达式的每一行来解决该问题,直到出现文本“第4行”,但是由于我认为会有很多行,因此必须有一种更简单的方法?
其他答案很好,但是如果您只需要在开始时进行匹配,则使用此方法:
var string_of_text = `03:47:06 This is line 1
03:47:07 This is line 2
03:47:08 This is line 3
03:47:09 This is line 4
This is line 5
03:47:10 This is line 6
03:47:11 This is line 7
This is line 8 03:33:12`;
var start_timestamp = string_of_text.match(/^([\:\d]){8}/gm)
["03:47:06", "03:47:07", "03:47:08", "03:47:09", "03:47:10", "03:47:11"]
就是说,根据您的评论,我猜您正在尝试将返回的时间与行相匹配...?在这种情况下,您应该先分割行:
string_of_text.split('\n').map(v=>(v.match(/^([\:\d]){8}/g)||[''])[0]);
0: "03:47:06"
1: "03:47:07"
2: "03:47:08"
3: "03:47:09"
4: ""
5: "03:47:10"
6: "03:47:11"
7: ""
如果您需要在任何地方进行匹配,只需从正则表达式中删除^
:
string_of_text.split('\n').map(v=>(v.match(/([\:\d]){8}/g)||[''])[0]);
0: "03:47:06"
1: "03:47:07"
2: "03:47:08"
3: "03:47:09"
4: ""
5: "03:47:10"
6: "03:47:11"
7: "03:33:12"
说明:
string_of_text
.split('\n') // Split into an array of lines.
.map( // Replace each entry with a new one using the given function.
v => ( v.match(/([\:\d]){8}/g) || [''] )[0] // Each array item (v) is searched for the pattern.
// If not found, null is returned, so default to an array with an empty string.
);
使用正则表达式:
([\d+|:]+) This is line 4
https://regex101.com/r/39qC3F/2
仅使用“第4行”进行编辑:
([\d+|:]+)[\w ]*line 4[\w ]*
https://regex101.com/r/39qC3F/3
使用示例:
const pattern = 'line 4';
const regex = new RegExp(`([\\d+|:]+)[\\w ]*${pattern}[\\w ]*`, 'gm');
const str = `03:47:06 This is line 1
03:47:07 This is line 2
03:47:08 This is line 3
03:47:09 This is line 4
This is line 5
03:47:10 This is line 6
03:47:11 This is line 7
This is line 8`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}