正则表达式仅匹配字符或空格或两个单词之间的一个点,不允许双倍空格

时间:2014-06-03 05:06:15

标签: javascript regex

我需要正则表达式的帮助。我需要JavaScript中的表达式,它只允许字符或空格或两个单词之间的一个点,不允许双倍空格。

我正在使用此

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

但它不起作用。

示例

1.  hello space .hello - not allowed
2.  space hello space - not allowed

4 个答案:

答案 0 :(得分:5)

试试这个:

^(\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: 如果你需要一些像

之间的空格或点
/^([\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 说明:

可能是\ s = [\ r \ n \ t \ f]中的问题 因此,如果只允许空格 - \s?可以替换为[ ]?

http://regex101.com/r/wV4yY5

答案 1 :(得分:3)

此正则表达式将匹配第一个单词之前或最后一个单词之后的单词和空格之间的多个空格或点。这与您想要的相反,但您始终可以将其反转(!foo.match(...)):

/\b[\. ]{2,}\b|^ | $/

在regex101.com中:http://regex101.com/r/fT0pF2

用更简洁的英语:

\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  that" // <= has two spaces
"this. that" // <= has dot space
" this that" // <= has space before first word
"this that " // <= has space after last word

但它不匹配:

"this.that and the other thing"

答案 2 :(得分:0)

那怎么样?

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

这允许:

  1. 多个前导空格。
  2. 空格作为分隔符。
  3. 点入第二个和任何连续的单词。

答案 3 :(得分:-1)

试试这个(单词之间只允许一个空格或句点):

> /\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