regex 使用正则表达式进行字符串验证

gjmwrych  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(100)

我需要为3个规则创建一个正则表达式。
1.字符串可以以字母或_开头。字母或_前不允许有数字。

  1. _可以添加到任何地方。
    1.不允许使用特殊字符或空格。
    我创建了两个正则表达式(^[A-Za-z0-9_]*$^[^0-9]*$),但不知道如何将它们合并组合在一起。此外,规则的末尾不包含数字(如_Sss12)。
_Aaa12 - correct
Aaa    - correct
aa aa  - fail
12aa   - fail
mlmc2os5

mlmc2os51#

就我所知,你想匹配一个 identifier

*必须从 * 字母 * A..Za..z_开始
*可以包含 * 字母 * A..Za..z_,或 * 数字 * 0..9

如果这是你的案子,

^[A-Za-z_][A-Za-z0-9_]*$

哪里

^             - anchor, start of the string
[A-Za-z_]     - Letter A..Z or a..z or symbol _
[A-Za-z0-9_]* - Zero or more letters, digits or _
$             - anchor, end of the string

如果字母可以是 * 任何Unicode* 字母,不需要拉丁字母,你可以使用\p{L}(对于任何Unicode数字,不需要0..9\d可以使用,但我怀疑你是否想要波斯语或印度语数字的模式):

^[\p{L}_][\p{L}0-9_]*$

相关问题