0

正则表达式:

"-[0-9]{0,}"

细绳:

"-abc"

根据这里的测试,这不应该发生。我假设我在代码中做错了什么。

代码:

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);
}

一些上下文:我使用的语音合成程序无法发音带有前导负号的数字,因此必须将其替换为“负”一词。

4

2 回答 2

5
-[0-9]{0,}

表示您的 sting 必须有-,然后可能是0more数字。

数字大小写-abc也是如此0

你没有指定,所以^ and $你的正则表达式匹配foo-bar甚至同样lll-0abc-

于 2013-03-29T09:41:27.610 回答
2

{0,}与 具有完全相同的含义*。因此,您的正则表达式的意思是“可以后跟数字的破折号” 。-abc包含破折号,因此可以找到该模式。

-\d+应该更好地满足您的需求(不要忘记转义 java: 的反斜杠-\\d+)。

如果您希望整个字符串与模式匹配,请使用^and $:锚定您的正则表达式^-\d+$

于 2013-03-29T09:41:46.233 回答