如何用正则仅替换button标签中的p-type属性为p-kind
要实现只修改<button>标签中的p-type属性为p-kind,同时保留其他标签内的p-type不变,可以用以下两种正则方案,适配不同的正则引擎:
方案1:使用正向后顾断言(支持可变长度后顾的引擎)
正则表达式:
(?<=<button[^>]*)\bp-type\b
替换为:
p-kind
说明:
(?<=<button[^>]*):正向后顾断言,确保匹配的p-type处于<button开头的标签属性区域内([^>]*匹配任意非>的字符,覆盖button标签的所有属性内容)\bp-type\b:匹配独立的p-type单词,避免误匹配包含该字符串的其他属性(如xp-type)
方案2:使用捕获组(兼容不支持可变长度后顾的旧版引擎)
正则表达式:
(<button[^>]*)\bp-type\b
替换为:
$1p-kind
说明:
(<button[^>]*):捕获button标签的前缀部分(从<button到p-type之前的所有内容)- 替换时保留捕获的前缀,仅将
p-type替换为p-kind
示例验证
输入:
<button p-type="foo"> anything </button> <div p-type="bar"> other content </div> <button class="btn" p-type="baz" id="test"> button with multiple attrs </button>
输出:
<button p-kind="foo"> anything </button> <div p-type="bar"> other content </div> <button class="btn" p-kind="baz" id="test"> button with multiple attrs </button>
内容的提问来源于stack exchange,提问作者ramos jc
相关产品推荐
相关产品推荐

