我试图使用正则表达式来匹配空格分隔的数字。 我找不到\b(“单词边界”)的精确定义。 我假设-12将是一个“整数词”(与\b\-?\d+\b匹配),但这似乎不起作用。如果能知道方法,我将不胜感激。

[我在Java 1.6中使用Java正则表达式]

例子:

Pattern pattern = Pattern.compile("\\s*\\b\\-?\\d+\\s*");
String plus = " 12 ";
System.out.println(""+pattern.matcher(plus).matches());

String minus = " -12 ";
System.out.println(""+pattern.matcher(minus).matches());

pattern = Pattern.compile("\\s*\\-?\\d+\\s*");
System.out.println(""+pattern.matcher(minus).matches());

这将返回:

true
false
true

当前回答

参考:精通正则表达式(Jeffrey E.F. Friedl) - O'Reilly

\b等价于(?<!\w)(?=\w)|(?<=\w)(?!\w)

其他回答

单词边界\b用于一个单词应该是单词字符,而另一个单词应该是非单词字符。 正则表达式应为负数

--?\b\d+\b

检查工作演示

我认为它是最后一个匹配或字符串的开始或结束的边界(即字符跟随)。

我在这里讨论了b风格正则表达式的边界。

简而言之,它们是有条件的。它们的行为取决于它们旁边的东西。

# same as using a \b before:
(?(?=\w) (?<!\w)  | (?<!\W) )

# same as using a \b after:
(?(?<=\w) (?!\w)  | (?!\W)  )

有时候这并不是你想要的。详见我的另一个答案。

查看关于边界条件的文档:

http://java.sun.com/docs/books/tutorial/essential/regex/bounds.html

看看这个例子:

public static void main(final String[] args)
    {
        String x = "I found the value -12 in my string.";
        System.err.println(Arrays.toString(x.split("\\b-?\\d+\\b")));
    }

当你把它打印出来时,注意输出是这样的:

[我发现值-,在我的字符串。]

这意味着“-”字符不会因为位于单词的边界而被拾取,因为它不被认为是单词字符。看来@brianary比我先下手为强,所以他得到了支持。

参考:精通正则表达式(Jeffrey E.F. Friedl) - O'Reilly

\b等价于(?<!\w)(?=\w)|(?<=\w)(?!\w)