【关键字】
TS / ArkTS / 正则表达式
【问题描述】
TS方法:
export class RegExpUtil {
static px2px(html: string): string {
html = "<span style='color:#333333; font-size: 15px;'><strong>车险</strong></span>";
const regex = /(\d+)px/;
const result = html.replace(regex, (match) => `${parseInt(match) * 2}px`);
return result
}
}
打印结果是:
<span style='color:#333333; font-size: 30px;'><strong>车险</strong></span>
ArkTS方法:
const html1 = "<span style='color:#333333; font-size: 15px;'><strong>车险</strong></span>";
const regex1: RegExp = new RegExp('/(\d+)px/');
const result1 = html1.replace(regex1, (match) => `${parseInt(match) * 2}px`);
打印结果是:
<span style='color:#333333; font-size: 15px;'><strong>车险</strong></span>
正则表达式不支持\d写法吗?使用[0-9]可以匹配到。
【解决方案】
正则表达式所有的转义字符都需要两个"\",然后首尾使用单双引号,而不使用"/"。
示例:
const html1 = "<span style='color:#333333; font-size: 15px;'><strong>车险</strong></span>";
const regex1: RegExp = new RegExp('(\\d+)px');
const result1 = html1.replace(regex1, (match) => `${parseInt(match) * 2}px`);
打印结果是:
<span style='color:#333333; font-size: 30px;'><strong>车险</strong></span>