I am pattern matching some strings to see if they match -
I want to accept
a b cde f ghijk lm n
but reject
a b cd ef g
since the latter has more than one whitespace character between tokens
I have this regex
new RegExp('^[a-zA-Z0-9\s?]+$', 'ig')
but it doesn't currently reject strings with more than 1 whitespace character between.
Is there any easy way to augment my current regex?
thanks
I am pattern matching some strings to see if they match -
I want to accept
a b cde f ghijk lm n
but reject
a b cd ef g
since the latter has more than one whitespace character between tokens
I have this regex
new RegExp('^[a-zA-Z0-9\s?]+$', 'ig')
but it doesn't currently reject strings with more than 1 whitespace character between.
Is there any easy way to augment my current regex?
thanks
Share Improve this question asked Mar 3, 2016 at 22:08 Alexander MillsAlexander Mills 100k166 gold badges537 silver badges918 bronze badges 2- 1 The answer can be found here: stackoverflow./questions/1630610/… – Cameron Meador Commented Mar 3, 2016 at 22:15
- @CameronMeador: Yes, it can be found, but not understood. The correct regex is not explained at all. Also, if there must be a support for leading/trailing whitespace, that post does not provide a working solution. – Wiktor Stribiżew Commented Mar 3, 2016 at 22:17
4 Answers
Reset to default 5Try this approach:
var str = "a b cde f ghijk lm n";
if(str.match(/\s\s+/)){
alert('it is not acceptable');
} else {
alert('it is acceptable');
}
Note: As @Wiktor Stribizew mentioned in the ment, maybe OP wants to reject string containing some symbols like this $
. So it would be better to use this regex in the condition:
/[^a-zA-Z0-9\s]|\s\s+/
Must you use regex? Why not just check to see if the string has two spaces?
JavaScript
strAccept = "a b c def ghijk lm n";
strReject = "a b cd ef g";
function isOkay(str) {
return str.indexOf(' ') == -1 && str.indexOf(' ') >= 0;
}
console.log(isOkay(strAccept))
console.log(isOkay(strReject))
Output
true
false
JS Fiddle: https://jsfiddle/igor_9000/ta216m3v/1/
Hope that helps!
Try following regex:
/^(\S+\s?)+$/im.test(text)
where parameter text
is whatever string you want to test.
OUTPUT:
a b cde f ghijk lm n <-- match
but reject <-- match
a b cd ef g <-- no match
See demo https://regex101./r/lS4cU7/2
If your tokens are just ASCII letters or digits, use
var regex = /^[a-z0-9]+(?:\s[a-z0-9]+)*$/i;
See the regex demo
The pattern matches:
^
- the start of string[a-z0-9]+
- one or more letters or digits(?:\s[a-z0-9]+)*
- 0+ sequences of:\s
- any whitespace, 1 symbol[a-z0-9]+
- 0+ letters or digits
$
- end of string
This way, you restrict the number of spaces between "words" to just 1 occurrence.
If you plan to allow leading/trailing whitespace, add \s*
after ^
and before $
.