使用正则表达式防止前导空格
我正在尝试使用(目前)以下正则表达式来限制评论发布文本:
^([a-zA-Z0-9 _\.\'\"\(\)\!\?\&\@]){1,}$
但是,文本本身需要包含“”形式的空格,但我不想允许第一个句子有空格,即帖子不能有前导空格。例如,(在下面的示例中我将使用 '_' 来表示 ' ')该表单允许:
这是一个句子。
但它不允许:
(使用'_'代表'')
_这是一个句子
__这是一个句子
等等
我尝试使用否定,但我只是不太了解正则表达式足以掌握如何做到这一点。整个领域都不适合我,所以希望有人能提供帮助。提前致谢!
笔记: 我在正则表达式中需要这个,因为我有一个实时反馈验证器告诉用户他/她的输入有效/无效。如果您碰巧想到更好的东西,另一种可以让我获得这种实时意识的选择将足以满足我的目的。
I'm trying to restrict review posting text with (at the present) the following RegEx:
^([a-zA-Z0-9 _\.\'\"\(\)\!\?\&\@]){1,}$
However, the text itself needs to contain whitespace in the form of ' ', but I don't want to allow the first sentence to have whitespace, i.e. the post cannot have leading whitespace. For an example, (I'm going to use '_' to represent ' ' in the following example) the form would allow:
This is a sentence.
But it would NOT allow:
(Using '_' to represent ' ')
_This is a sentence
__This is a sentence
etc.
I tried to work with negations, but I just don't understand RegEx well enough to grasp how to do this. This whole field is just not sitting well with me, so hopefully someone can help. Thanks in advance!
NOTE:
I need this in RegEx because I have a live-feed validator telling the user that his/her input is valid/invalid. Another option that will allow me this real-time awareness will be sufficient for my purposes, if you happen to think of something better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以使用负向预测:
You can also use a negative lookahead:
如果您只想允许这些字符,但限制第一个字符不应是空格,则必须重复字符组:
或者进行两个测试:
If you only want to allow these characters with the restriction that the first one should not be a whitespace, you have to repeat the character group:
Or you make two tests:
只需在正则表达式的开头使用 ^\S 即可,其中“^”是字符串的开头,“\S”是空白字符类的否定。
Just use ^\S at the beginning of your regex, where the '^' is the beginning of the string, and '\S' is the negation of the whitespace character class.