gpt4 book ai didi

javascript - 正则表达式返回整行

转载 作者:行者123 更新时间:2023-11-30 09:35:38 33 4
gpt4 key购买 nike

所以,我有一个字符串,当该行包含我正在搜索的词时,我想返回整行。我有这段代码:

var subtitle = '4'+
'00:00:24.067 --> 00:00:35.924'+
'Hi, how are you?'+
'Doing fine?'+
''+
'5'+
'00:00:35.926 --> 00:00:47.264'+
'I\'m doing the best I can.'+
'And you?';

var myRe = /^.* you.*$/ig;
var myArray;
while ((myArray = myRe.exec(legenda)) !== null) {
var msg = 'Found ' + myArray[0] + '. ';
msg += 'Next match starts at ' + myRe.lastIndex;
console.log(msg);
}

在上面的代码中,我试图返回包含单词“you”的两行,预期输出将是:“嗨,你好吗?”和“你呢?”但我得到了字幕变量的所有内容。但是,如果我检查我的正则表达式 here我得到了想要的输出。

有人可以帮帮我吗?这是我第一次使用正则表达式,感觉有点迷茫。

最佳答案

首先,这不是多行字符串,您只是将多行字符串连接起来,但字符串本身是单行。然后,当尝试将多行字符串与正则表达式匹配时,您必须使用 m flag

检查这个问题:Creating multiline strings in JavaScript

var subtitle = '4\n'+
'00:00:24.067 --> 00:00:35.924\n'+
'Hi, how are you?\n'+
'Doing fine?\n'+
'\n'+
'5\n'+
'00:00:35.926 --> 00:00:47.264\n'+
'I\'m doing the best I can.\n'+
'And you?\n';

var myRe = /^.* you.*$/igm;
var myArray;
while ((myArray = myRe.exec(subtitle)) !== null) {
var msg = 'Found ' + myArray[0] + '. ';
msg += 'Next match starts at ' + myRe.lastIndex;
console.log(msg);
}

关于javascript - 正则表达式返回整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43724070/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com