Regular expression to match only character or space or one dot between two words, no double space allowed
14,128
Solution 1
try this:
^(\s?\.?[a-zA-Z]+)+$
EDIT1
/^(\s{0,1}\.{0,1}[a-zA-Z]+)+$/.test('space ..hello space')
false
/^(\s{0,1}\.{0,1}[a-zA-Z]+)+$/.test('space .hello space')
true
v2:
/^(\s?\.?[a-zA-Z]+)+$/.test('space .hello space')
true
/^(\s?\.?[a-zA-Z]+)+$/.test('space ..hello space')
false
v3: if you need some thisn like one space or dot between
/^([\s\.]?[a-zA-Z]+)+$/.test('space hello space')
true
/^([\s\.]?[a-zA-Z]+)+$/.test('space.hello space')
true
/^([\s\.]?[a-zA-Z]+)+$/.test('space .hello space')
false
v4:
/^([ \.]?[a-zA-Z]+)+$/.test('space hello space')
true
/^([ \.]?[a-zA-Z]+)+$/.test('space.hello space')
true
/^([ \.]?[a-zA-Z]+)+$/.test('space .hello space')
false
/^([ ]?\.?[a-zA-Z]+)+$/.test('space .hello space')
true
EDIT2 Explanation:
may be problem in \s = [\r\n\t\f ]
so if only space allowed - \s?
can be replaced with [ ]?
Solution 2
This regular expression will match multiple spaces or dots between words and spaces before the first word or after the last word. This is the opposite of what you want, but you can always invert it (!foo.match(...)
):
/\b[\. ]{2,}\b|^ | $/
In regex101.com: http://regex101.com/r/fT0pF2
And in plainer english:
\b => a word boundary
[\. ] => a dot or a space
{2,} => 2 or more of the preceding
\b => another word boundary
| => OR
^{space} => space after string start
| => OR
{space}$ => space before string end
This will match:
"this that" // <= has two spaces
"this. that" // <= has dot space
" this that" // <= has space before first word
"this that " // <= has space after last word
But it will not match:
"this.that and the other thing"
Author by
user3291547
Updated on June 28, 2022Comments
-
user3291547 almost 2 years
I need help with regular expression.I need a expression in JavaScript which allows only character or space or one dot between two words, no double space allowed.
I am using this
var regexp = /^([a-zA-Z]+\s)*[a-zA-Z]+$/;
but it's not working.
Example
1. hello space .hello - not allowed 2. space hello space - not allowed