如何正则表达式匹配整个字符串而不是单个字符 [英] How to regex match entire string instead of a single character
问题描述
我正在尝试使用 JavaScript 正则表达式 /[\u0600-\u06FF]/
按照 这篇文章.我只想接受阿拉伯字母字符和空格.
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屋!