正则表达式查找空间

Ald*_*ldo 10 regex space

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

小智 17

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

可以找到空白区域\s.

如果要在单词之间找到空格,请使用\b单词边界标记.

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

"\b \b"
Run Code Online (Sandbox Code Playgroud)

(你的匹配失败的原因是\\p{L}包含匹配中的字符.因为e只有一个字符,它会被前一个匹配吃掉,并且不能匹配后面的空格e. \b避免这个问题因为它是零宽度比赛.)


Cap*_*awk 5

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


zia*_*zia 5

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