public static void main(String[] args) throws Exception {
// Create a pattern to match cat
Pattern p = Pattern.compile("#[\\d]+#");
String[] aa = new String[]{"bbbb", "aaaa"};
// Create a matcher with an input string
Matcher m = p.matcher("one #0# two #1#s in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
// Loop through and create a new String
// with the replacements
while (result) {
String temp = m.group().substring(1, m.group().length() - 1);
m.appendReplacement(sb, aa[Integer.parseInt(temp)]);
result = m.find();
}
// Add the last segment of input to
// the new String
m.appendTail(sb);
System.out.println(sb.toString());
}
// Create a pattern to match cat
Pattern p = Pattern.compile("#[\\d]+#");
String[] aa = new String[]{"bbbb", "aaaa"};
// Create a matcher with an input string
Matcher m = p.matcher("one #0# two #1#s in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
// Loop through and create a new String
// with the replacements
while (result) {
String temp = m.group().substring(1, m.group().length() - 1);
m.appendReplacement(sb, aa[Integer.parseInt(temp)]);
result = m.find();
}
// Add the last segment of input to
// the new String
m.appendTail(sb);
System.out.println(sb.toString());
}
class RegexTest {
public static void main (String[] args ) { Pattern p = Pattern.compile("#([0-9]+)#");
// 如果匹配范围已知应该避免使用\\d, \\w这样的通配符
// 因为java使用递归来进行regex匹配,使用通配符容易导致溢出
String[] param = new String[]{"arg0", "arg1","arg2"};
String str = "abc #0# asd #1# asdf #d# #2# asdf #0#";
Matcher m = p.matcher ( str );
boolean find = m.find();
while ( find ) {
int i = Integer.parseInt ( m.group(1) );//找出应该被替换的序号,
// 这样即使#?#重复或者#?#次序颠倒也不要紧
try {
String currentParam = param [ i ];
str = m.replaceAll ( currentParam );
} catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println ( "No such argument! " );
}
m = p.matcher ( str );
find = m.find();
}
System.out.println ( str );
}
}