如何使用正则表达式将单词开头的每个数字替换为下划线字符,以及将单词其余部分中除字母、数字、破折号和点之外的所有字符替换为下划线?
我尝试了这个正则表达式:
^(\d+)|[^\w-.]
但是,它会将开头的所有数字替换为单个下划线字符。
因此,34567fgf-kl.)*/676hh
转换为 _fgf-kl.___676hh
而我需要将开头的每个数字替换为一个下划线字符就像_____fgf-kl.___676hh
。
是否可以使用正则表达式来实现?
最佳答案
您可以像这样将 Matcher.appendReplacement
与 Matcher.find
一起使用:
String fileText = "34567fgf-kl.)*/676hh";
String pattern = "^\\d+|[^\\w.-]+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(fileText);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, repeat("_", m.group(0).length()));
}
m.appendTail(sb); // append the rest of the contents
System.out.println(sb);
重复
是
public static String repeat(String s, int n) {
if(s == null) {
return null;
}
final StringBuilder sb = new StringBuilder(s.length() * n);
for(int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();
}
参见 IDEONE demo
此外,可以使用 Commons Lang StringUtils.repeat() 将 repeat
替换为 Stringrepeated = StringUtils.repeat("_", m.group(0).length());
。
关于Java正则表达式替换开头的每个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32018881/