Javascript 正则表达式只匹配字符或空格或两个单词之间的一个点,不允许使用双空格
我需要正则表达式的帮助。我需要一个JavaScript表达式,它只允许字符或空格或两个单词之间的一个点,不允许双空格 我在用这个Javascript 正则表达式只匹配字符或空格或两个单词之间的一个点,不允许使用双空格,javascript,regex,Javascript,Regex,我需要正则表达式的帮助。我需要一个JavaScript表达式,它只允许字符或空格或两个单词之间的一个点,不允许双空格 我在用这个 var regexp = /^([a-zA-Z]+\s)*[a-zA-Z]+$/; 但它不起作用 示例 1. hello space .hello - not allowed 2. space hello space - not allowed 试试这个: ^(\s?\.?[a-zA-Z]+)+$ EDIT1 /^(\s{0,1}\.{0,1}[a-zA-Z
var regexp = /^([a-zA-Z]+\s)*[a-zA-Z]+$/;
但它不起作用
示例
1. hello space .hello - not allowed
2. space hello space - not allowed
试试这个:
^(\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:
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:
EDIT2
说明:
可能是\s=[\r\n\t\f]中的问题
因此,如果只允许空间-\s?
可以替换为[]?
试试这个(单词之间只允许有一个空格或句点):
此正则表达式将在单词和第一个单词之前或最后一个单词之后的空格之间匹配多个空格或点。这与您想要的正好相反,但您始终可以将其反转(
!foo.match(…)
):
在regex101.com中:
用更简单的英语:
\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
怎么样
^\s*([a-zA-Z]+\s?\.?[a-zA-Z]+)+$
这允许:
$-表示字符串的结尾,在正则表达式中也没有破折号。你到底需要得到什么?结束空格,也没有破折号示例测试。我不允许谁放-1,为什么?我不确定。我的猜测是因为你的建议没有解释,而且你的答案中有拼写和格式错误。所以你的建议是寻找非法州,而问题的作者是关于积极方法的。你是对的。我应该说清楚的。我很早就决定可靠地发现问题会更容易。>>不允许出现双空格。我不确定你想说什么。他/她是否希望允许使用双空格?我的理解是,它们不应该被允许。如果不起作用,我只需要允许字符开始空格和点,例如1。abcd.ab 2。空间,空间,像这样也许你能更清楚一点你的意思。你能用引号引用几个合法和非法值的例子吗:
“this is legal”
,“this.not”
或其他什么?我想我们都不明白你到底想做什么。请用你所有的输入更新Q,在你的例子中使用引号?所以允许多个或单个空格前导?我需要示例:“this is.testing”,“more spaces this.is testing”,“this is.testing”我得到了答案。谢谢你的回复。
/\b[\. ]{2,}\b|^ | $/
\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"
^\s*([a-zA-Z]+\s?\.?[a-zA-Z]+)+$