我正在尝试从 OCR 契约(Contract)中提取段落(如果该段落包含使用 JS 的关键搜索术语)。用户可能会搜索“提前发货”之类的内容来查找与特定客户订单是否可以提前发货相关的条款。
我已经用头撞正则表达式墙很长一段时间了,但显然我没有捕获一些东西。
如果我有这样的文本并且我正在搜索单词“match”:
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'
]
任何帮助都会很棒。
最佳答案
如果您使用 .
默认情况下匹配除换行符之外的所有字符这一事实,那就非常容易了。使用正则表达式 /.*match.*/
两边都有贪婪的 .*
:
const text = 'aaaa\n\nbbb match ccc\n\nddd';
const regex = /.*match.*/;
console.log(text.match(regex).toString());
输出:
bbb match ccc
关于javascript - 提取包含换行符之间匹配的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66146805/