正则表达式包含字母数字和 _ [英] Regex to include alphanumeric and _
问题描述
我正在尝试创建一个正则表达式来匹配字母数字字符和下划线 _
.这是我的正则表达式:"\w_*[^-$\s\]"
我的印象是这个正则表达式表示任何字母数字字符 \w
,下划线 _
,并且没有 -
、$
或空格.这是正确的吗?
I'm trying to create a regular expression to match alphanumeric characters and the underscore _
. This is my regex: "\w_*[^-$\s\]"
and my impression is that this regex means any alphanumeric character \w
, an underscore _
, and no -
,$
, or whitespace. Is this correct?
推荐答案
正则表达式被读作实际匹配字符串中字符的模式,从左到右,因此您的模式实际上匹配一个字母数字,然后是下划线(0 或更多), THEN 至少有一个不是连字符、美元或空格的字符.
Regular expressions are read as patterns which actually match characters in a string, left to right, so your pattern actually matches an alphanumeric, THEN an underscore (0 or more), THEN at least one character that is not a hyphen, dollar, or whitespace.
由于您尝试更改字符类型,因此只需使用字符类来显示您允许使用的字符:
Since you're trying to alternate on character types, just use a character class to show what characters you're allowing:
[\w_]
这会检查字符串的任何部分是否与它匹配,因此让我们将其锚定到字符串的开头和和:
This checks that ANY part of the string matches it, so let's anchor it to the beginning and and of the string:
^[\w_]$
现在我们看到字符类缺少量词,所以我们只匹配一个字符.我们可以使用 +
(如果你想要一个或多个字符,没有空字符串)或 *
(如果你想允许空字符串)来解决这个问题.我将在这里使用 +
.
And now we see that the character class lacks a quantifier, so we are matching on exactly ONE character. We can fix that using +
(if you want one or more characters, no empty strings) or *
(if you want to allow empty strings). I'll use +
here.
^[\w_]+$
事实证明,\w
字符类已经包含下划线,因此我们可以从模式中删除多余的下划线:
As it turns out, the \w
character class already includes the underscore, so we can remove the redundant underscore from the pattern:
^[\w]+$
现在我们在字符类中只有一个字符,所以我们根本不再需要字符类括号:
And now we have only one character in the character class, so we no longer need the character class brackets at all:
^\w+$
这就是您所需要的,除非我遗漏了您的要求.
And that's all you need, unless I'm missing something about your requirements.
这篇关于正则表达式包含字母数字和 _的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!