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?
Add a comment
|
3 Answers
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.)
2 Comments
Aldo
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?
Maybe I'm not tracking, but why not just use [ ]?
1 Comment
Abhinav Saxena
I used stringVar.contains(" "). It works, but I have to experiment with the expressions: "\b \b" and "\s".
// 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;