正则表达式查找空间

时间:2013-06-06 14:50:01

标签: regex space

我有以下文字=“superilustrado e de capa dura?”,我想在文本中找到单词之间的所有空格。我使用以下表达式= [\\p{L}[:punct:]][[:space:]][\\p{L}[:punct:]]。表达式工作正常,但它可以找到“e de”之间的空格。有人知道我的正则表达式有什么问题吗?

3 个答案:

答案 0 :(得分:16)

只需在正则表达式中添加空格字符即可找到空格。

可以在\s找到空格。

如果要查找单词之间的空格,请使用\b单词边界标记。

这将匹配两个单词之间的单个空格:

"\b \b"

(你的匹配失败的原因是\\p{L}包含匹配中的字符。因为e只有一个字符,它会被前一个匹配吃掉而无法匹配e之后的空格。\b可以避免此问题,因为它是零宽度匹配。)

答案 1 :(得分:4)

也许我没有跟踪,但为什么不使用[]?

答案 2 :(得分:0)

// Setup
var testString = "How many spaces are there in this sentence?";

// Only change code below this line.

var expression = /\s+/g;  // Change this line

// Only change code above this line

// This code counts the matches of expression in testString
var spaceCount = testString.match(expression).length;
相关问题