A regular expression to match only a character or a space or one dot between two words, double space is not allowed

I need help with regex. I need an expression in JavaScript that allows only a character or space or a single dot between two words, double space is not allowed.

I use this

var regexp = /^([a-zA-Z]+\s)*[a-zA-Z]+$/; 

but it does not work.

Example

 1. hello space .hello - not allowed 2. space hello space - not allowed 
+6
source share
4 answers

try the following:

 ^(\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 kind of it, like one space or a point 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:

can be a problem in \ s = [\ r \ n \ t \ f] therefore, if only the space - \s? allowed \s? can be replaced by [ ]?

http://regex101.com/r/wV4yY5

+4
source

This regular expression will correspond to several 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|^ | $/ 

At regex101.com: http://regex101.com/r/fT0pF2

And in a more understandable 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" 
+3
source

How about this?

 ^\s*([a-zA-Z]+\s?\.?[a-zA-Z]+)+$ 

This allows:

  • A few leading spaces.
  • Space as a delimiter.
  • A point in the second and any consecutive word.
0
source

Try it (only one space or period is allowed between spaces):

 > /\w+[\s\.]\w+/.test('foo bar') true > /\w+[\s\.]\w+/.test('foo.bar') true > /\w+[\s\.]\w+/.test('foo..bar') false > /\w+[\s\.]\w+/.test('foo .bar') false 
-1
source

Source: https://habr.com/ru/post/970219/


All Articles