16

I have the following text = "superilustrado e de capa dura?", and I want to find all the spaces between words in the text. I am using the following expression = [\\p{L}[:punct:]][[:space:]][\\p{L}[:punct:]]. The expression works fine but it can find the space between the "e de". Does anybody know what is the problem with my regular expression?

3 Answers 3

30

Spaces can be found simply by putting a space character in your regex.

Whitespace can be found with \s.

If you want to find whitespace between words, use the \b word boundary marker.

This would match a single space between two words:

"\b \b"

(The reason your match failed is that \\p{L} includes the character in a match. Because e is only one character, it gets eaten up by the previous match and can't be matched for the space after e. \b avoids this problem because it is a zero-width match.)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, your explanation makes sense. However, when I use the expression with a text that has punctuation, "Já imaginou seu filho publicar um livro de verdade, superilustrado e de capa dura? Então, vá preparando a festa de lançamento deste bestseller! Seu filho vai ter um livro escrito e ilustrado por ele mesmo!", it doesn't find all the spaces. Is there a way to include another expression that takes care of punctuation?
@Aldo, why not just search for all the spaces in the string? Are there other spaces that you don't want to match?
6

Maybe I'm not tracking, but why not just use [ ]?

1 Comment

I used stringVar.contains(" "). It works, but I have to experiment with the expressions: "\b \b" and "\s".
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.