正则表达式:
"-[0-9]{0,}"
Run Code Online (Sandbox Code Playgroud)
串:
"-abc"
Run Code Online (Sandbox Code Playgroud)
根据这里的测试,这不应该发生.我假设我在代码中做错了.
码:
public static void main(String[] args) {
String s = "-abc";
String regex = "-[0-9]{0,}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
if (matcher.group().length() == 0)
break;
// get the number less the dash
int beginIndex = matcher.start();
int endIndex = matcher.end();
String number = s.substring(beginIndex + 1, endIndex);
s = s.replaceFirst(regex, "negative " + number);
}
System.out.println(s);
}
Run Code Online (Sandbox Code Playgroud)
一些上下文:我使用的语音合成程序不能发出带有前导负号的数字,因此必须用"否定"一词替换.
-[0-9]{0,}
Run Code Online (Sandbox Code Playgroud)
意味着你的刺痛必须有-,然后可能是0或more数字.
所以-abc是0一些案例
你没有指定^ and $,所以你的正则表达式匹配foo-bar,lll-0甚至abc-也是如此