REGEX 用于匹配开始和结束跨度标签,而无需其内部文本
我正在使用以下正则表达式在字符串中进行替换:
<\/?(span)\b(?:\s+class="highlight")?>
但是这个正则表达式有一个缺陷...以这个示例代码为例:
<p>
Some text here
<span class="highlight">This is highlighted</span>
<span>This is not highlighted</span>
</p>
我的正则表达式将匹配两个 span 标签,尽管我只想要带有 class=" 的一个突出显示”设置。如何使用正则表达式实现这一目标?
PS:请不要告诉我我不应该为此使用正则表达式,因为我会降低你的答案,因为它是偏离主题的。这是 RegEx 人员的问题。
编辑:根据下面接受的答案,我使用以下正则表达式进行替换 注意:代码位于 javascript (mootools) 中
var regex = new RegExp("(<span[^>]+class\\s*=\\s*(\"|')highlight\\2[^>]*>)(.*?)(</span>)",'g');
var replaced = element.get('html').replace(regex, "$3");
element.set('html', replaced);
上面的正则表达式将用“此处的一些文本”替换此处的一些文本(不带双引号)
I am using the following RegEx to do a replacement in a string:
<\/?(span)\b(?:\s+class="highlight")?>
But this regex has a flaw... Take this sample code for example:
<p>
Some text here
<span class="highlight">This is highlighted</span>
<span>This is not highlighted</span>
</p>
My regex will match both of the span tags although i only want the one with the class="highlight" set. How can I achieve this using RegEx?
PS: please do not tell me that I should not use RegEx for this because i will downgrade your answer as it is off-topic. This is a question for the RegEx guys.
EDIT: based on the accepted answer below i am using the following regex to do a replace
NOTE: code is in javascript (mootools)
var regex = new RegExp("(<span[^>]+class\\s*=\\s*(\"|')highlight\\2[^>]*>)(.*?)(</span>)",'g');
var replaced = element.get('html').replace(regex, "$3");
element.set('html', replaced);
The above regex will replace a some text here with "some text here" (without the double quotes)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该提供最大的灵活性。
更新:
开始和结束标记所需的捕获组是 \1 和 \3。
This should give the most flexibility.
UPDATE:
The captured groups you need for the opening and closing tags are \1 and \3.
只是为了向您展示替代解决方案不仅是可能的,而且比使用正则表达式更好:
请参阅此小提琴:http://jsfiddle.net/Tomalak/umgZp/
(这只是我的想象,到目前为止我对 MooTools 的接触为零。可能还有更多比这更优雅的方式。)
Just to show you that an alternative solution is not only possible bot also better than using regex:
See this fiddle: http://jsfiddle.net/Tomalak/umgZp/
(And this is just off the top of my hat, I've had zero exposure to MooTools so far. There might be more elegant ways than this.)
您显然是在声明
class=highlight
部分是可选的,通过在捕获它的组前面放置?
。这应该可以为您完成:
这还将包括具有类属性的 SPAN 标记,例如
abc height ef g
。另外,如果您想捕获具有匹配结尾的 SPAN 标记,您可以使用此标记,并分别访问组 1 和 3 作为开始标记和结束标记:
You are obviously stating that that
class=highlight
part is optional, by placing a?
in front of the group capturing it.This should do it for you:
This will also include SPAN tags with class attributes like
a b c highlight e f g
.Also, if you want to capture a SPAN tag with its matching ending, you can use this, and access groups 1 and 3 respectively for the opening and ending tags: