【问题标题】:Extract text containing match between new line characters提取包含换行符之间匹配的文本
【发布时间】:2021-05-14 17:25:13
【问题描述】:

如果该段落包含使用 JS 的关键搜索词,我正在尝试从 OCR 合同中提取段落。用户可能会搜索诸如“提前发货”之类的内容来查找与某个客户的订单是否可以提前发货相关的条款。

我已经把头撞在正则表达式墙上很长一段时间了,显然我没有抓住什么。

如果我有这样的文字并且我正在搜索“匹配”这个词:

let text = "\n\nThis is an example of a paragraph that has the word I'm looking for The word is Match. \n\nThis paragraph does not have the word I want."

我想提取双 \n 字符之间的所有文本,而不是返回该字符串中的第二个句子。

我一直在尝试某种形式:

let string = `[^\n\n]*match[^.]*\n\n`;

let re = new RegExp(string, "gi");
let body = text.match(re);

但是,它返回 null。奇怪的是,如果我从它工作的字符串中删除句点(排序):

[
  "This is an example of a paragraph that has the word I'm looking for The word is Match \n" +
    '\n'
]

任何帮助都会很棒。

【问题讨论】:

  • 试试这个:[^\n].*match.*[^\n]。编辑:我猜这个?可能是? \n{2,}(.*match.*)\n{2,}

标签: javascript node.js regex regex-lookarounds regex-group


【解决方案1】:

如果没有与上下文匹配相关的任何技巧,则不太可能在包含某些特定文本的相同分隔符之间提取一些文本。

因此,您可以简单地将文本分成段落并获得包含匹配项的段落:

const results = text.split(/\n{2,}/).filter(x=>/\bmatch\b/i.test(x))

如果您不需要整个单词匹配,您可以删除单词边界。

查看 JavaScript 演示:

let text = "\n\nThis is an example of a paragraph that has the word I'm looking for The word is Match. \n\nThis paragraph does not have the word I want.";
console.log(text.split(/\n{2,}/).filter(x=>/\bmatch\b/i.test(x)));

【讨论】:

  • 太棒了 - 谢谢!!如果我想让搜索词动态化怎么办?模板文字似乎不起作用。
【解决方案2】:

如果您使用 . 默认匹配除换行符以外的所有字符这一事实,那将非常容易。在两边使用正则表达式/.*match.*/ 和贪婪的.*

const text = 'aaaa\n\nbbb match ccc\n\nddd';
const regex = /.*match.*/;
console.log(text.match(regex).toString());

输出:

bbb match ccc

【讨论】:

    【解决方案3】:

    这里有两种方法。我不知道为什么你需要使用正则表达式。拆分似乎更容易做到,不是吗?

    const text = "\n\nThis is an example of a paragraph that has the word I'm looking for The word is Match. \n\nThis paragraph does not have the word I want."
    
    // regular expression one
    
    function getTextBetweenLinesUsingRegex(text) {
      const regex = /\n\n([^(\n\n)]+)\n\n/;
      const arr = regex.exec(text);
      if (arr.length > 1) {
        return arr[1];
      }
      return null;
    }
    
    console.log(`getTextBetweenLinesUsingRegex: ${ getTextBetweenLinesUsingRegex(text)}`);
    
    console.log(`simple: ${text.split('\n\n')[1]}`); 

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 2020-11-13
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多