cwe*_*ton 2 java regex regex-group
我不确定这是否可行,但我需要一种方法来替换我的regex表达式中指定的编号组的值,使用在运行时动态声明的字符串,一旦匹配完成.
鉴于一个简单的案例,像......
(/)?([A-Za-z0-9])?(/)?$
Run Code Online (Sandbox Code Playgroud)
我希望能够为第2组插入替代品.
我目前正在使用Java的Matcher类.
我不确定这是否可行......
是的,这是可能的.请参阅下面的示例.
我希望能够为第2组插入替代品.
此演示"插入"第.toUpperCase2组的版本作为替代.
import java.util.regex.*;
class Main {
public static void main(String... args) {
String input = "hello my name is /aioobe/ and I like /patterns/.";
Pattern p = Pattern.compile("(/)([A-Za-z0-9]+)(/)");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String rep = m.group(1) + m.group(2).toUpperCase() + m.group(3);
m.appendReplacement(sb, rep);
}
m.appendTail(sb);
System.out.println(sb);
}
}
Run Code Online (Sandbox Code Playgroud)
打印:
hello my name is /AIOOBE/ and I like /PATTERNS/.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6013 次 |
| 最近记录: |