正则表达式问题

whyxx 2004-04-15 11:18:43
各位大哥.小弟最近学习正则表达式.有一个问题,不知道能否用正则表达式来解决.
比如有一个字符串:String str = "abc #1# asd #2# asdf #d# #3# asdf"
另有一个字符串数组:String[] params = new String(){"aaa","bbb","ccc","ddd"}
需要的结果是到str里找到类似#n#这种东西,然后将其替换成params[n],也就是说
#1# 替换成:params[1], #2#替换成params[2].
...全文
45 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
duracell 2004-04-15
  • 打赏
  • 举报
回复
import java.util.regex.*;
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 );
}
}
XIHSHI 2004-04-15
  • 打赏
  • 举报
回复
up
CuZnRong 2004-04-15
  • 打赏
  • 举报
回复
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());
}
whyxx 2004-04-15
  • 打赏
  • 举报
回复
to: duracell() 不好意思,我给完分,才看到你回答了.

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧