如何将<input type="button">标签替换为含其value属性值的${}格式字符串
替换需求实现方案
核心实现逻辑为通过正则匹配所有<input type="button"开头的自闭合标签,捕获标签内value属性的属性值,将整个标签替换为${xxx}格式(xxx为捕获到的value值),以下是不同常用开发语言的实现示例:
JavaScript 实现
const originalStr = 'the quick <input type="button" disabled="" value="brown.fox" /> jumps over the <input type="button" disabled="" value="lazy.dog" />'; // 全局匹配符合要求的input标签并替换 const result = originalStr.replace(/<input\s+type="button"\s+[^>]*?value="([^"]+)"[^>]*\/?>/g, '${$1}'); console.log(result);
输出结果:
the quick ${brown.fox} jumps over the ${lazy.dog}
Python 实现
import re original_str = 'the quick <input type="button" disabled="" value="brown.fox" /> jumps over the <input type="button" disabled="" value="lazy.dog" />' result = re.sub(r'<input\s+type="button"\s+[^>]*?value="([^"]+)"[^>]*\/?>', r'${\1}', original_str) print(result)
正则说明
- 适配属性顺序不固定的场景,只要是
type="button"的input标签都能匹配 - 捕获组对应value属性的双引号包裹内容,只要value值本身不包含双引号就可正常匹配
- 支持匹配末尾带/不带斜杠的自闭合input标签
内容的提问来源于stack exchange,提问作者baba-dev
相关产品推荐
相关产品推荐

