- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我有一个具有挑战性的问题要解决。我正在编写一个将正则表达式作为输入的脚本。然后,此脚本会在文档中查找此正则表达式的所有匹配项,并将每个匹配项包装在其自己的 元素中。困难的部分是文本是格式化的 html 文档,因此我的脚本需要在 DOM 中导航并同时在多个文本节点上应用正则表达式,同时确定在需要时必须在何处拆分文本节点。
例如,使用正则表达式捕获以大写字母开头并以句点结尾的完整句子,此文档:
<p>
<b>HTML</b> is a language used to make <b>websites.</b>
It was developed by <i>CERN</i> employees in the early 90s.
<p>
会变成这样:
<p>
<span><b>HTML</b> is a language used to make <b>websites.</b></span>
<span>It was developed by <i>CERN</i> employees in the early 90s.</span>
<p>
然后脚本返回所有创建的 span 的列表。
我已经有一些代码可以找到所有文本节点并将它们连同它们在整个文档中的位置和深度一起存储在一个列表中。你真的不需要理解那些代码来帮助我,它的递归结构可能有点令人困惑。 我不确定该怎么做的第一部分是弄清楚哪些元素应该包含在范围内。
function SmartNode(node, depth, start) {
this.node = node;
this.depth = depth;
this.start = start;
}
function findTextNodes(node, depth, start) {
var list = [];
var start = start || 0;
depth = (typeof depth !== "undefined" ? depth : -1);
if(node.nodeType === Node.TEXT_NODE) {
list.push(new SmartNode(node, depth, start));
} else {
for(var i=0; i < node.childNodes.length; ++i) {
list = list.concat(findTextNodes(node.childNodes[i], depth+1, start));
if(list.length) start += list[list.length-1].node.nodeValue.length;
}
}
return list;
}
我想我会从所有文档中生成一个字符串,通过它运行正则表达式并使用列表来查找哪些节点对应于女巫正则表达式匹配,然后相应地拆分文本节点。
但是当我有这样的文档时,问题就来了:
<p>
This program is <a href="beta.html">not stable yet. Do not use this in production yet.</a>
</p>
有一个句子开始于 <a>
之外标签但在其中结束。现在我不希望脚本将该链接分成两个标签。在更复杂的文档中,它可能会破坏页面。代码可以将两个句子包装在一起:
<p>
<span>This program is <a href="beta.html">not stable yet. Do not use this in production yet.</a></span>
</p>
或者只是将每个部分包装在它自己的元素中:
<p>
<span>This program is </span>
<a href="beta.html">
<span>not stable yet.</span>
<span>Do not use this in production yet.</span>
</a>
</p>
可以有一个参数来指定它应该做什么。我只是不确定如何确定何时将发生不可能的切割,以及如何从中恢复。
另一个问题是当我在像这样的子元素中有空格时:
<p>This is a <b>sentence. </b></p>
从技术上讲,正则表达式匹配将在句点之后结束,在 <b>
结束之前标签。然而,将空格视为匹配的一部分并像这样包装它会更好:
<p><span>This is a <b>sentence. </b></span></p>
比这个:
<p><span>This is a </span><b><span>sentence.</span> </b></p>
但这是一个小问题。毕竟,我可以只允许在正则表达式中包含额外的空白。
我知道这听起来像是一个“帮我做”的问题,而不是我们每天在 SO 上看到的那种快速问题,但我已经坚持了一段时间,这是一个开放的问题-我正在处理的源库。解决这个问题是最后一个障碍。如果您认为另一个 SE 站点最适合回答这个问题,请重定向我。
最佳答案
这里有两种方法可以解决这个问题。
我不知道以下内容是否完全符合您的需求。这是一个足够简单的问题解决方案,但至少它不使用 RegEx 来操作 HTML 标记。它对原始文本执行模式匹配,然后使用 DOM 来操作内容。
这种方法只创建一个 <span>
标记每个匹配项,利用一些不太常见的浏览器 API。
(看demo下面这个方法的主要问题,如果不确定就用第二种方法)。
Range
类代表一个文本片段。它有一个 surroundContents
允许您将范围包装在元素中的函数。除了它有一个警告:
This method is nearly equivalent to
newNode.appendChild(range.extractContents()); range.insertNode(newNode)
. After surrounding, the boundary points of the range includenewNode
.An exception will be thrown, however, if the
Range
splits a non-Text
node with only one of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail.
好吧,MDN 中提供了解决方法,所以一切都很好。
所以这是一个算法:
Text
节点并在文本中保留它们的起始索引text
在文本中查找匹配项,对于每个匹配项:
Range
在比赛中这是我的演示实现:
function highlight(element, regex) {
var document = element.ownerDocument;
var getNodes = function() {
var nodes = [],
offset = 0,
node,
nodeIterator = document.createNodeIterator(element, NodeFilter.SHOW_TEXT, null, false);
while (node = nodeIterator.nextNode()) {
nodes.push({
textNode: node,
start: offset,
length: node.nodeValue.length
});
offset += node.nodeValue.length
}
return nodes;
}
var nodes = getNodes(nodes);
if (!nodes.length)
return;
var text = "";
for (var i = 0; i < nodes.length; ++i)
text += nodes[i].textNode.nodeValue;
var match;
while (match = regex.exec(text)) {
// Prevent empty matches causing infinite loops
if (!match[0].length)
{
regex.lastIndex++;
continue;
}
// Find the start and end text node
var startNode = null, endNode = null;
for (i = 0; i < nodes.length; ++i) {
var node = nodes[i];
if (node.start + node.length <= match.index)
continue;
if (!startNode)
startNode = node;
if (node.start + node.length >= match.index + match[0].length)
{
endNode = node;
break;
}
}
var range = document.createRange();
range.setStart(startNode.textNode, match.index - startNode.start);
range.setEnd(endNode.textNode, match.index + match[0].length - endNode.start);
var spanNode = document.createElement("span");
spanNode.className = "highlight";
spanNode.appendChild(range.extractContents());
range.insertNode(spanNode);
nodes = getNodes();
}
}
// Test code
var testDiv = document.getElementById("test-cases");
var originalHtml = testDiv.innerHTML;
function test() {
testDiv.innerHTML = originalHtml;
try {
var regex = new RegExp(document.getElementById("regex").value, "g");
highlight(testDiv, regex);
}
catch(e) {
testDiv.innerText = e;
}
}
document.getElementById("runBtn").onclick = test;
test();
.highlight {
background-color: yellow;
border: 1px solid orange;
border-radius: 5px;
}
.section {
border: 1px solid gray;
padding: 10px;
margin: 10px;
}
<form class="section">
RegEx: <input id="regex" type="text" value="[A-Z].*?\." /> <button id="runBtn">Highlight</button>
</form>
<div id="test-cases" class="section">
<div>foo bar baz</div>
<p>
<b>HTML</b> is a language used to make <b>websites.</b>
It was developed by <i>CERN</i> employees in the early 90s.
<p>
<p>
This program is <a href="beta.html">not stable yet. Do not use this in production yet.</a>
</p>
<div>foo bar baz</div>
</div>
好吧,那是惰性方法,不幸的是,它在某些情况下不起作用。如果您仅突出显示内联元素,它会很好地工作,但由于 extractContents
的以下属性,当沿途有 block 元素时会中断功能:
Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid.
这很糟糕。它只会复制 block 级节点。使用 baz\s+HTML
尝试之前的演示正则表达式,如果你想看看它是如何中断的。
此方法迭代匹配节点,创建 <span>
一路上的标签。
整个算法很简单,因为它只是将每个匹配节点包装在自己的 <span>
中。 .但这意味着我们必须处理部分匹配的文本节点,这需要更多的努力。
如果一个文本节点部分匹配,它将与 splitText
分开功能:
After the split, the current node contains all the content up to the specified offset point, and a newly created node of the same type contains the remaining text. The newly created node is returned to the caller.
function highlight(element, regex) {
var document = element.ownerDocument;
var nodes = [],
text = "",
node,
nodeIterator = document.createNodeIterator(element, NodeFilter.SHOW_TEXT, null, false);
while (node = nodeIterator.nextNode()) {
nodes.push({
textNode: node,
start: text.length
});
text += node.nodeValue
}
if (!nodes.length)
return;
var match;
while (match = regex.exec(text)) {
var matchLength = match[0].length;
// Prevent empty matches causing infinite loops
if (!matchLength)
{
regex.lastIndex++;
continue;
}
for (var i = 0; i < nodes.length; ++i) {
node = nodes[i];
var nodeLength = node.textNode.nodeValue.length;
// Skip nodes before the match
if (node.start + nodeLength <= match.index)
continue;
// Break after the match
if (node.start >= match.index + matchLength)
break;
// Split the start node if required
if (node.start < match.index) {
nodes.splice(i + 1, 0, {
textNode: node.textNode.splitText(match.index - node.start),
start: match.index
});
continue;
}
// Split the end node if required
if (node.start + nodeLength > match.index + matchLength) {
nodes.splice(i + 1, 0, {
textNode: node.textNode.splitText(match.index + matchLength - node.start),
start: match.index + matchLength
});
}
// Highlight the current node
var spanNode = document.createElement("span");
spanNode.className = "highlight";
node.textNode.parentNode.replaceChild(spanNode, node.textNode);
spanNode.appendChild(node.textNode);
}
}
}
// Test code
var testDiv = document.getElementById("test-cases");
var originalHtml = testDiv.innerHTML;
function test() {
testDiv.innerHTML = originalHtml;
try {
var regex = new RegExp(document.getElementById("regex").value, "g");
highlight(testDiv, regex);
}
catch(e) {
testDiv.innerText = e;
}
}
document.getElementById("runBtn").onclick = test;
test();
.highlight {
background-color: yellow;
}
.section {
border: 1px solid gray;
padding: 10px;
margin: 10px;
}
<form class="section">
RegEx: <input id="regex" type="text" value="[A-Z].*?\." /> <button id="runBtn">Highlight</button>
</form>
<div id="test-cases" class="section">
<div>foo bar baz</div>
<p>
<b>HTML</b> is a language used to make <b>websites.</b>
It was developed by <i>CERN</i> employees in the early 90s.
<p>
<p>
This program is <a href="beta.html">not stable yet. Do not use this in production yet.</a>
</p>
<div>foo bar baz</div>
</div>
我希望这对于大多数情况应该足够好了。如果你需要最小化 <span>
的数量标记它可以通过扩展这个函数来完成,但我现在想保持简单。
关于javascript - 如何使用 JavaScript 将部分文本包装在节点中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31275446/
我需要将文本放在 中在一个 Div 中,在另一个 Div 中,在另一个 Div 中。所以这是它的样子: #document Change PIN
奇怪的事情发生了。 我有一个基本的 html 代码。 html,头部, body 。(因为我收到了一些反对票,这里是完整的代码) 这是我的CSS: html { backgroun
我正在尝试将 Assets 中的一组图像加载到 UICollectionview 中存在的 ImageView 中,但每当我运行应用程序时它都会显示错误。而且也没有显示图像。 我在ViewDidLoa
我需要根据带参数的 perl 脚本的输出更改一些环境变量。在 tcsh 中,我可以使用别名命令来评估 perl 脚本的输出。 tcsh: alias setsdk 'eval `/localhome/
我使用 Windows 身份验证创建了一个新的 Blazor(服务器端)应用程序,并使用 IIS Express 运行它。它将显示一条消息“Hello Domain\User!”来自右上方的以下 Ra
这是我的方法 void login(Event event);我想知道 Kotlin 中应该如何 最佳答案 在 Kotlin 中通配符运算符是 * 。它指示编译器它是未知的,但一旦知道,就不会有其他类
看下面的代码 for story in book if story.title.length < 140 - var story
我正在尝试用 C 语言学习字符串处理。我写了一个程序,它存储了一些音乐轨道,并帮助用户检查他/她想到的歌曲是否存在于存储的轨道中。这是通过要求用户输入一串字符来完成的。然后程序使用 strstr()
我正在学习 sscanf 并遇到如下格式字符串: sscanf("%[^:]:%[^*=]%*[*=]%n",a,b,&c); 我理解 %[^:] 部分意味着扫描直到遇到 ':' 并将其分配给 a。:
def char_check(x,y): if (str(x) in y or x.find(y) > -1) or (str(y) in x or y.find(x) > -1):
我有一种情况,我想将文本文件中的现有行包含到一个新 block 中。 line 1 line 2 line in block line 3 line 4 应该变成 line 1 line 2 line
我有一个新项目,我正在尝试设置 Django 调试工具栏。首先,我尝试了快速设置,它只涉及将 'debug_toolbar' 添加到我的已安装应用程序列表中。有了这个,当我转到我的根 URL 时,调试
在 Matlab 中,如果我有一个函数 f,例如签名是 f(a,b,c),我可以创建一个只有一个变量 b 的函数,它将使用固定的 a=a1 和 c=c1 调用 f: g = @(b) f(a1, b,
我不明白为什么 ForEach 中的元素之间有多余的垂直间距在 VStack 里面在 ScrollView 里面使用 GeometryReader 时渲染自定义水平分隔线。 Scrol
我想知道,是否有关于何时使用 session 和 cookie 的指南或最佳实践? 什么应该和什么不应该存储在其中?谢谢! 最佳答案 这些文档很好地了解了 session cookie 的安全问题以及
我在 scipy/numpy 中有一个 Nx3 矩阵,我想用它制作一个 3 维条形图,其中 X 轴和 Y 轴由矩阵的第一列和第二列的值、高度确定每个条形的 是矩阵中的第三列,条形的数量由 N 确定。
假设我用两种不同的方式初始化信号量 sem_init(&randomsem,0,1) sem_init(&randomsem,0,0) 现在, sem_wait(&randomsem) 在这两种情况下
我怀疑该值如何存储在“WORD”中,因为 PStr 包含实际输出。? 既然Pstr中存储的是小写到大写的字母,那么在printf中如何将其给出为“WORD”。有人可以吗?解释一下? #include
我有一个 3x3 数组: var my_array = [[0,1,2], [3,4,5], [6,7,8]]; 并想获得它的第一个 2
我意识到您可以使用如下方式轻松检查焦点: var hasFocus = true; $(window).blur(function(){ hasFocus = false; }); $(win
我是一名优秀的程序员,十分优秀!