相关疑难解决方法(0)

正则表达式中的单词边界是什么?

我在Java 1.6中使用Java正则表达式(尤其是解析数字输出)并且找不到\b("单词边界")的精确定义.我假设这-12将是一个"整数字"(匹配 \b\-?\d+\b),但似乎这不起作用.我很想知道匹配空格分隔数字的方法.

例:

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());
Run Code Online (Sandbox Code Playgroud)

返回:

true
false
true
Run Code Online (Sandbox Code Playgroud)

regex word-boundary

107
推荐指数
8
解决办法
12万
查看次数

以特殊字符开头或结尾的单词的单词边界会产生意想不到的结果

假设我想匹配短语Sortes\index[persons]{Sortes}中短语的存在test Sortes\index[persons]{Sortes} text

使用 pythonre我可以做到这一点:

>>> search = re.escape('Sortes\index[persons]{Sortes}')
>>> match = 'test Sortes\index[persons]{Sortes} text'
>>> re.search(search, match)
<_sre.SRE_Match object; span=(5, 34), match='Sortes\\index[persons]{Sortes}'>
Run Code Online (Sandbox Code Playgroud)

这有效,但我想避免搜索模式Sortes对短语给出肯定的结果test Sortes\index[persons]{Sortes} text

>>> re.search(re.escape('Sortes'), match)
<_sre.SRE_Match object; span=(5, 11), match='Sortes'>
Run Code Online (Sandbox Code Playgroud)

所以我使用\b模式,像这样:

search = r'\b' + re.escape('Sortes\index[persons]{Sortes}') + r'\b'
match = 'test Sortes\index[persons]{Sortes} text'
re.search(search, match)
Run Code Online (Sandbox Code Playgroud)

现在,我没有得到匹配。

如果搜索模式不包含任何字符[]{},则它有效。例如:

>>> re.search(r'\b' + re.escape('Sortes\index') + r'\b', 'test Sortes\index test')
<_sre.SRE_Match object; span=(5, 17), match='Sortes\\index'>
Run Code Online (Sandbox Code Playgroud)

另外,如果我删除 …

python regex

7
推荐指数
1
解决办法
1067
查看次数

标签 统计

regex ×2

python ×1

word-boundary ×1