【问题标题】:Regex match a sentence in a paragraph that contains new lines正则表达式匹配包含换行符的段落中的句子
【发布时间】:2018-05-02 08:00:53
【问题描述】:

我基本上在 html div 中有一段文本。通过单击/激活按钮,我想突出显示一定长度的文本。因此,我需要找到它的索引并向它们添加 class=highlight 的跨度。

因此,我想匹配一个innerHtml文本中的句子,例如:

var text = "The quick brown fox jumps over the lazy dog".

但是,该段落可能会将句子分成多行,例如:

innerHTML = 
"The quick brown 
fox jumps over 
the lazy dog"

而且我不能以任何方式“修改”innerHTML,例如从文本中删除空格/换行符。

我似乎无法想到或找到正确的正则表达式序列来实现这一点。

这不起作用:

var search_regexp = new RegExp(text, 'm');
innerHTML.search(search_regexp);

【问题讨论】:

  • 比赛结束后你想做什么?
  • 我基本上在 html div 中有一段文本。通过单击/激活按钮,我想突出显示一定长度的文本。因此,我需要找到它的索引并向它们添加带有 class=highlight 的“s”。
  • 感谢大家的帮助!西蒙布拉汉的回答成功了。不幸的是,我无法显示我的赞成票,因为它说我在这个新帐户中的声誉少于 15 个。

标签: javascript regex multiline


【解决方案1】:

你可以replace换行空格match

var fnReplaceLR = ( str ) => str.replace(/\s+/g, " " ); //method to replace line-breaks and other consecutive multiple spaces with single space.
var text = "The quick brown fox jumps over the lazy dog";
var innerHTML = 
`The quick brown 
fox jumps over 
the lazy dog`;
var search_regexp = new RegExp( fnReplaceLR( text ) ); //no need for m modifier now
fnReplaceLR( innerHTML ).match( search_regexp ); //match the string

演示

var fnReplaceLR = (str) => str.replace(/\s+/g, " "); //method to replace line-breaks and other consecutive multiple spaces with single space.
var text = "The quick brown fox jumps over the lazy dog";
var innerHTML =
  `The quick brown 
    fox jumps over 
    the lazy dog`;
var search_regexp = new RegExp(fnReplaceLR(text)); //no need for m modifier now
var output = fnReplaceLR(innerHTML).match(search_regexp); //match the string
console.log(output);

【讨论】:

  • 谢谢@gurvinder372。不幸的是,我不能通过不破坏(或“替换”)内部 HTML 文本来做到这一点。还有另一种方法可以通过正则表达式字符串来实现吗?
【解决方案2】:

当您搜索单词之间的任何空格(不仅仅是空格)时,您需要将搜索模式中的空格替换为通用空格标记。这将起作用:

var regex = text.split(/\s+/).join('\\s+');
var search_regexp = new RegExp(text, 'm');
innerHTML.search(search_regexp);

split(/\s+/).join('\\s+')的效果是:

  1. 将输入文本拆分为任意数量的空格,生成单词数组,
  2. \s+ 正则表达式标记连接单词,它匹配一个或多个空白字符。这包括换行符和制表符。

【讨论】:

  • 没问题。如果它能给你你所需要的,请在答案上打勾;帮助其他有同样问题的人,并给我甜蜜的互联网积分。
【解决方案3】:

嗯,这就是我会做的。

只需将文本按\n 拆分,然后与" " 连接即可为其提供单行句子格式。现在您可以使用.includes 来检查您要匹配的文本是否是其他文本的一部分

var text = "The quick brown fox jumps over the lazy dog",
    stringWithBreakLines = `The quick brown
fox jumps over
the lazy dog
this is some additional
text in html`;
 
console.log(stringWithBreakLines.split("\n").join(" ").includes(text))

【讨论】:

  • 感谢@George Bailey。不幸的是,我不能通过不破坏(或“替换”)内部 HTML 文本来做到这一点。还有另一种方法可以通过正则表达式字符串来实现吗?
  • 这里没有被替换。你的 innerHTML 将保持不变
  • .split 不会更改原始数组。相反,它返回一个新数组
  • 啊,我明白了。谢谢乔治。我认为过多地忽略了问题的背景是我的错误。基本上我需要有句子在原始innerHTML 中位置的索引,这样我就可以找到文本并在其中添加“spans”。我已经编辑了我的问题陈述..
猜你喜欢
  • 2018-10-13
  • 2023-03-08
  • 1970-01-01
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 2013-10-27
  • 1970-01-01
相关资源
最近更新 更多