【问题标题】:Regex returning entire line正则表达式返回整行
【发布时间】:2017-05-02 02:19:45
【问题描述】:

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

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”的两行,预期的输出将是:“嗨,你好吗?” “你呢?”但我得到了 subtitle 变量的所有内容。 但是,如果我检查我的正则表达式 here,我会得到想要的输出。

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

【问题讨论】:

  • 这不是多行字符串。它是多行的,因为您的代码是多行,但字符串本身不是。字符串中没有一个换行符。
  • 变量subtitle 是一个没有换行符的完整字符串。
  • 你说得对,我会改正的!

标签: javascript regex


【解决方案1】:

首先,这不是多行字符串,您只是将一个字符串连接成多行,但字符串本身是单行。然后,当尝试将多行字符串与正则表达式匹配时,您必须使用 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);
            }

【讨论】:

    【解决方案2】:

    我检查了你的正则表达式链接。正如你所说,它给出了预期的结果。我验证了,它捕获了两个不同的组。该站点还提供代码生成工具,在同一站点的左侧边栏中签入?
    我已经用 Javascript 为您完成了它,并且也进行了测试。如果您想使用任何其他语言,请自行生成。如果您遇到任何困难,请发表评论。 :)

    const regex = /^.* you.*$/gmi;
    const str = `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?
    `;
    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}`);
        });
    }
    

    【讨论】:

    • 我没有意识到它有这个功能!此代码有效,感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多