Dej*_*ell 3 java regex variables
我有以下字符串:
<div height="40px" width="30px" />
Run Code Online (Sandbox Code Playgroud)
我想用正则表达式替换所有具有px的数字,其后面的X值为其值.(X是变量).
因此,如果X = 3,结果将是
<div height="120px" width="90px" />
Run Code Online (Sandbox Code Playgroud)
请注意,X必须是我将检索到该函数的变量
下面的代码将取代30px与240pxString中的s使用正则表达式:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Example {
public static void main(String[] args) {
String s = "abc 30px def";
int var = 8;
Pattern patt = Pattern.compile("([0-9]+)px");
Matcher m = patt.matcher(s);
StringBuffer sb = new StringBuffer(s.length());
while (m.find()) {
int px = Integer.parseInt(m.group(1));
String next = String.valueOf(var * px) + "px";
m.appendReplacement(sb, Matcher.quoteReplacement(next));
}
m.appendTail(sb);
System.out.println(sb.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
以下是它执行的步骤:
s匹配项和每个匹配项:
var.px再次追加并将其作为替换字符串传递.| 归档时间: |
|
| 查看次数: |
210 次 |
| 最近记录: |