JavaScript正则表达式捕获和替换可选部分

时间:2014-08-26 14:34:49

标签: javascript regex

我发现在[{1}} Capture and Replace中跟Regex的关注行发现JavaScript时很难:

// Lines:
This is <span>foo</span>.
This is <span>(Capital) foo</span>.
This is <span>foo (Plural)</span>.
This is <span>(Capital) foo (Plural)</span>.

上述所有内容我都需要This is foo.

我试过:

var pattern = /<span>(\(Capital\))?\s?(\w+)\s?(\(Plural\))?<\/span>/;

var text1 = "This is <span>foo</span>";
var text2 = "This is <span>(Capital) foo</span>";
var text3 = "This is <span>foo (Plural)</span>";
var text4 = "This is <span>(Capital) foo (Plural)</span>";

text1.replace(pattern, function(_, m){ return m; });
text2.replace(pattern, function(_, m){ return m; });
text3.replace(pattern, function(_, m){ return m; });
text4.replace(pattern, function(_, m){ return m; });

但它不起作用。

3 个答案:

答案 0 :(得分:1)

如果<>()之间的内容无关紧要,那么:

text.replace(/[<(][^>)]+[>)]/g, '').replace(/ {2,}/g, ' ');

(添加了第二个替换,确保没有留下双重空格)

答案 1 :(得分:1)

您可以使用以下正则表达式

<span>(?:\(Capital\))?\s*(\w+)\s*(?:\(Plural\))?<\/span>

将匹配的字符替换为组索引1中的字符。

DEMO

> "This is <span>foo</span>.".replace(/<span>(?:\(Capital\))?\s*(\w+)\s*(?:\(Plural\))?<\/span>/g, '$1');
'This is foo.'
> "This is <span>(Capital) foo</span>.".replace(/<span>(?:\(Capital\))?\s*(\w+)\s*(?:\(Plural\))?<\/span>/g, '$1');
'This is foo.'
> "This is <span>foo (Plural)</span>.".replace(/<span>(?:\(Capital\))?\s*(\w+)\s*(?:\(Plural\))?<\/span>/g, '$1');
'This is foo.'
> "This is <span>(Capital) foo (Plural)</span>.".replace(/<span>(?:\(Capital\))?\s*(\w+)\s*(?:\(Plural\))?<\/span>/g, '$1');
'This is foo.'

答案 2 :(得分:0)

您可以将正则表达式修改为:

var r = str.replace(/(?:</?span>| *\((?:Capital|Plural)\)) */gmi, "");

RegEx Demo