如何正则表达式匹配整个字符串而不是单个字符 [英] How to regex match entire string instead of a single character

查看:238
本文介绍了如何正则表达式匹配整个字符串而不是单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试按照

I am trying to implement "alpha" validation on Arabic alphabet characters input, using the JavaScript regex /[\u0600-\u06FF]/ as instructed in this post. I want to accept only Arabic alphabet characters and spaces.

现在的问题是它给出了以下结果:

Now the problem is it gives the following result:

r = /[\u0600-\u06FF]/

r.test("abcd")      // false - correct
r.test("@#$%^")     // false - correct
r.test("س")         // true  - correct
r.test("abcd$$#5س") // true  - should be false
r.test("abcdس")     // true  - should be false

如果给出单个匹配字符,则它将整个输入分类为可接受,即使输入的其余部分充满了不可接受的字符.我应该改用什么正则表达式?

If a single matching character is given, then it is classifying the whole input as acceptable, even if the rest of the input is full of unacceptable chars. What regex should I be using instead?

推荐答案

您需要在正则表达式中添加^$锚,以及一个+以允许多个字符.

You need to add ^ and $ anchors to the regular expression, as well as a + to allow multiple characters.

尝试一下:

/^[\u0600-\u06FF]+$/

我不确定您提到的阿拉伯语空格"是否包含在该字符范围内,但是如果您想在字符串中允许空格,则只需在[]括号内添加一个\s即可.

I'm not sure if "Arabic spaces" that you mentioned are included in the character range there, but if you want to allow white space in the string then just add a \s inside the [] brackets.

这篇关于如何正则表达式匹配整个字符串而不是单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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