Javascript正则表达式 - 开头没有空格+允许中间空格 [英] Javascript regex - no white space at beginning + allow space in the middle

查看:709
本文介绍了Javascript正则表达式 - 开头没有空格+允许中间空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个正则表达式,它与字符串匹配,一开始没有空格。但是包含中间空格的字符串可以匹配。到目前为止我已尝试过以下

I would like to have a regex which matches the string with NO whitespace(s) at the beginning. But the string containing whitespace(s) in the middle CAN match. So far i have tried below

[^-\s][a-zA-Z0-9-_\\s]+$

Debuggex演示

上面不允许在开头使用空格,但也不允许在字符串的中间/末尾。请帮帮我。

Above is not allowing whitespace(s) at the beginning, but also not allowing in the middle/end of the string. Please help me.

推荐答案

在你的第二个角色课上, \\\\ 将匹配 \ s ,而不是 \s 。因此它与空白不匹配。你应该只使用 \s 。另外,将连字符移到末尾,否则会在字符类中创建无意识的范围:

In your 2nd character class, \\s will match \ and s, and not \s. Thus it doesn't matches a whitespace. You should use just \s there. Also, move the hyphen towards the end, else it will create unintentional range in character class:

^[^-\s][a-zA-Z0-9_\s-]+$

这篇关于Javascript正则表达式 - 开头没有空格+允许中间空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆