简体   繁体   English

跳过正则表达式html中的标签和空格

[英]Skipping over tags and spaces in regex html

I'm using this regex to find a String that starts with !?, ends with ?!, and has another variable inbetween (in this example "a891d050"). 我正在使用此正则表达式查找一个以!?开头,以?!结尾的字符串,并且中间还有另一个变量(在此示例中为“ a891d050”)。 This is what I use: 这是我用的:

var pattern = new RegExp(/!\\?.*\s*(a891d050){1}.*\s*\\?!/);

It matches correctly agains this one: 它正确地匹配了这个:

!?v8qbQ5LZDnFLsny7VmVe09HJFL1/WfGD2A:::a891d050?! 

But fails when the string is broken up with html tags. 但是当用html标签将字符串分解时失败。

<span class="userContent"><span>!?v8qbQ5LZDnFLsny7VmVe09HJFL1/</span><wbr /><span class="word_break"></span>WfGD2A:::a891d050?!</span></div></div></div></div>

I tried adding \\s and {space} * , but it still fails. 我尝试添加\\ s{space} * ,但是仍然失败。 The question is, what (special?)characters do I need to account for if I want to ignore whitespace and html tags in my match. 问题是,如果我想忽略比赛中的空白和html标签,我需要考虑哪些(特殊?)字符。

edit: this is how I use the regex: 编辑:这就是我使用正则表达式的方式:

var pattern = /!\?[\s\S]*a891d050[\s\S]*\?!/;

document.body.innerHTML = document.body.innerHTML.replace(pattern,"new content");

It appears to me that when it encounters the 'plain' string it replaces is correctly. 在我看来,当它遇到替换为'plain'的字符串时,它是正确的。 But when faced with String with classes around it and inside, it makes a mess of the classes or doesn't replace at all depending on the context. 但是,当面对String及其周围和内部的类时,它会使这些类弄乱, 或者完全不能根据上下文替换。 So I decided to try jquery-replacetext-plugin (as it promises to leave tags as they were) like this: 因此,我决定尝试使用jquery-replacetext-plugin (因为它保证将标签保持原样)是这样的:

$("body *").replaceText( pattern, "new content" );

But with no success, the results are the same as before. 但是没有成功,结果与以前相同。

Maybe this: 也许这样:

var pattern = /!\?[\s\S]*a891d050[\s\S]*\?!/;

[\\s\\S] should match any character. [\\ s \\ S]应该与任何字符匹配。 I have also removed {1}. 我还删除了{1}。

使用此正则表达式显然可以解决该问题:

var pattern = /(!\?)(?:<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])*?>)?(.)*?(a891d050)(?:<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])*?>)?(.)*?(\?!)/;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM