正则表达式中的单词边界是什么? [英] What is a word boundary in regex?
问题描述
我正在尝试使用正则表达式来匹配以空格分隔的数字.我找不到 (词边界")的精确定义.我曾假设
-12
将是一个整数词".(由 -?d+
匹配)但似乎这不起作用.我很高兴知道 .
I'm trying to use regexes to match space-separated numbers.
I can't find a precise definition of ("word boundary").
I had assumed that
-12
would be an "integer word" (matched by -?d+
) but it appears that this does not work. I'd be grateful to know of ways of .
[我在 Java 1.6 中使用 Java 正则表达式]
[I am using Java regexes in Java 1.6]
示例:
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
推荐答案
在大多数正则表达式方言中,单词边界是 w
和 W
之间的位置(非单词字符),或者在字符串的开头或结尾,如果它以单词字符([0-9A-Za-z_]
)开头或结尾(分别).
A word boundary, in most regex dialects, is a position between w
and W
(non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ([0-9A-Za-z_]
).
因此,在字符串 "-12"
中,它会匹配 1 之前或 2 之后.破折号不是单词字符.
So, in the string "-12"
, it would match before the 1 or after the 2. The dash is not a word character.
这篇关于正则表达式中的单词边界是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!