本文介绍了用于验证用户名的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个正则表达式来验证用户名。



用户名可能包含:




  • 字母(西方,希腊,俄罗斯等)

  • 数字

  • 空格, / li>
  • 特殊字符(例如:!@#$%^& *。:;<>?/ \ | {} [] _ + = - ),但每次只能有1个



编辑:



对不起,




  • 我需要它可可触摸,但我必须翻译它php为服务器端无论如何。

  • 每次使用1表示空格或特殊字符应以字母或数字分隔。


解决方案

代替编写一个大的正则表达式,更清楚地写出单独的正则表达式来测试每个所需的条件。




  • 测试用户名是否只包含字母,数字,ASCII符号通过 code>和空格: ^(\p {L} | \p {N} | [! - @] |)+ $ 。这必须匹配用户名才有效。注意对于Unicode字母和 \p {N} 类使用 \p {L}


  • 测试用户名是否包含连续空格: \s\s +


  • 测试符号是否连续出现: [! - @] [! - @] + 。如果匹配,用户名无效。





$ b

但是,根据用户名的写法,完全有效的名称,如éponine仍然可能被这种方法拒绝。这是因为É可以写成U + 00C9拉丁资本E与ACUTE(匹配 \p {L} )或像 E 后跟U + 02CA MODIFIER LETTER ACUTE ACCENT( 匹配 \p {L} 。)



Unicode是多毛的,限制用户名中的字符不一定是个好主意。您确定要这么做吗?


I'm looking for a regular expression to validate a username.

The username may contain:

  • Letters (western, greek, russian etc.)
  • Numbers
  • Spaces, but only 1 at a time
  • Special characters (for example: "!@#$%^&*.:;<>?/\|{}[]_+=-") , but only 1 at a time

EDIT:

Sorry for the confusion

  • I need it for cocoa-touch but i'll have to translate it for php for the server side anyway.
  • And with 1 at a time i mean spaces or special char's should be separated by letters or numbers.

解决方案

Instead of writing one big regular expression, it would be clearer to write separate regular expressions to test each of your desired conditions.

  • Test whether the username contains only letters, numbers, ASCII symbols ! through @, and space: ^(\p{L}|\p{N}|[!-@]| )+$. This must match for the username to be valid. Note the use of the \p{L} class for Unicode letters and the \p{N} class for Unicode numbers.

  • Test whether the the username contains consecutive spaces: \s\s+. If this matches, the username is invalid.

  • Test whether symbols occur consecutively: [!-@][!-@]+. If this matches, the username is invalid.

This satisfies your criteria exactly as written.

However, depending on how the usernames have been written, perfectly valid names like "Éponine" may still be rejected by this approach. This is because the "É" could be written either as U+00C9 LATIN CAPITAL E WITH ACUTE (which is matched by \p{L}) or something like E followed by U+02CA MODIFIER LETTER ACUTE ACCENT (which is not matched by \p{L}.)

Regular-Expressions.info says it better:

Unicode is hairy, and restricting the characters in usernames is not necessarily a good idea anyway. Are you sure you want to do this?

这篇关于用于验证用户名的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 04:42