【问题标题】:Regex - Extract string between square bracket tag [duplicate]正则表达式 - 在方括号标记之间提取字符串 [重复]
【发布时间】:2019-05-06 06:15:17
【问题描述】:

我有像[note]some text[/note] 这样的字符串标签,我想在其中提取标签之间的内部文本。

示例文本:

Want to extract data [note]This is the text I want to extract[/note] 
but this is not only tag [note]Another text I want to [text:sample] 
extract[/note]. Can you do it?

从给定的文本中,提取以下内容:

This is the text I want to extract

Another text I want to [text:sample] extract

【问题讨论】:

    标签: javascript php regex


    【解决方案1】:

    我们可以尝试使用以下正则表达式进行匹配:

    \[note\]([\s\S]*?)\[\/note\]
    

    这表示只捕获[note] 和最接近的关闭[/note] 标记之间的任何内容。请注意,如果有必要,我们会使用 [\s\S]* 来匹配所需的内容。

    var re = /\[note\]([\s\S]*?)\[\/note\]/g;
    var s = 'Want to extract data [note]This is the text I want to extract[/note]\nbut this is not only tag [note]Another text I want to [text:sample]\n extract[/note]. Can you do it?';
    var m;
    
    do {
        m = re.exec(s);
        if (m) {
            console.log(m[1]);
        }
    } while (m);

    【讨论】:

      【解决方案2】:

      我在蒂姆发布他的答案时写了这个,这很像,但我想我还是会发布它,因为它被提取到一个可重用的函数中,你可以将它用于任何标签。

      const str = `Want to extract data [note]This is the text I want to extract[/note] 
      but this is not only tag [note]Another text I want to [text:sample] 
      extract[/note]. Can you do it?`;
      
      function extractTagContent(tag, str) {
        const re = new RegExp(`\\[${tag}\\](.*?)\\[\\/${tag}\\]`, "igs");
        const matches = [];
        let found;
        while ((found = re.exec(str)) !== null) {
          matches.push(found[1]);
        }
        return matches;
      }
      
      const content = extractTagContent("note", str);
      // content now has:
      // ['This is the text I want to extract', 'Another text I want to [text:sample] extract. Can you do it?']
      

      演示:https://codesandbox.io/s/kw006560oo

      【讨论】:

        猜你喜欢
        • 2011-11-04
        • 2018-07-30
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-17
        • 2010-09-29
        相关资源
        最近更新 更多