我发现在[{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; });
但它不起作用。
答案 0 :(得分:1)
如果<>
或()
之间的内容无关紧要,那么:
text.replace(/[<(][^>)]+[>)]/g, '').replace(/ {2,}/g, ' ');
(添加了第二个替换,确保没有留下双重空格)
答案 1 :(得分:1)
您可以使用以下正则表达式
<span>(?:\(Capital\))?\s*(\w+)\s*(?:\(Plural\))?<\/span>
将匹配的字符替换为组索引1中的字符。
> "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)