开发者

Regular Expression - Only match Alphanumerics and a SINGLE whitespace between words

I'm new to Regular Expressions... I've been asked a regular expression that accepts Alphanumerics, a few characters more, and only ONE whitespace between words.

For example : This should match :

"Hello world"

This shouldn't :

"Hello  world"

Any ideas?

This was my expression开发者_如何转开发:

[\w':''.'')''(''\[''\]''{''}''-''_']+$

I already tried the \s? (the space character once or never - right? ) but I didn't get it to work.


Using Oniguruma regex syntax, you could do something like:

^[\w\.:\(\)\[\]{}\-_](?: ?[\w\.:\(\)\[\]{}\-_])*$

Assuming that the 'other characters' are . : () [] {} - _

This regex will match a string that must begin and end with a word character or one of the other allowed characters and cannot have more than one space in a row.

If you're using the x flag (ignore whitespace in regular expression) you'll need to do this instead:

^[\w\.:\(\)\[\]{}\-_](?:\ ?[\w\.:\(\)\[\]{}\-_])*$

The only difference is the \ in front of the space.


What about:

^[\w\.:\(\)\[\]{}\-]+( [\w\.:\(\)\[\]{}\-]+)*$

Matches:

  • ^[\w\.:\(\)\[\]{}\-]+: line begins with 1 or more acceptable characters (underscore is included in \w).
  • ( [\w\.:\(\)\[\]{}\-]+): look to include a single separator character and 1 or more acceptable characters.
  • *$: repeat single separator and word 0 or more times.

Tested:

  • Hello(space)World: TRUE
  • Hello(space)(space)World: FALSE
  • Hello: TRUE
  • Hello(space): FALSE
  • Hello(tab)World: FALSE
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜