Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match only character or space or one dot between two words, no double space allowed

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
like image 705
user3291547 Avatar asked Jun 03 '14 05:06

user3291547


1 Answers

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 [ ]?

http://regex101.com/r/wV4yY5

like image 107
Subdigger Avatar answered Oct 19 '22 00:10

Subdigger