gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:03:10 24 4
gpt4 key购买 nike

我发现很难在 JavaScript 中使用 Regex 对以下行执行捕获和替换:

// 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; });

但它不起作用。

最佳答案

您可以使用下面的正则表达式,

<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.'

关于JavaScript 正则表达式捕获并替换可选部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25508516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com