正则表达式查找空间

问题描述 投票:7回答:3

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

regex space
3个回答
16
投票

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

可以在\s找到空白。

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

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

"\b \b"

(你的比赛失败的原因是\\p{L}包含了比赛中的角色。因为e只有一个角色,它被前一场比赛吃掉,而且在e之后无法匹配.\b避免了这个问题,因为它是零宽度匹配。)


4
投票

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


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;
© www.soinside.com 2019 - 2024. All rights reserved.