简体   繁体   English

字母数字字符串的正则表达式,下划线不应是第一个或最后一个字符

[英]Regular expression for alphanumeric string, underscore should not be a first or last character

我想有一个正则表达式,检查字符串是否只包含大写和小写字母,数字和下划线,但下划线不应该是字符串中的第一个或最后一个字符,我在下面尝试使用Python。

"^[a-zA-Z0-9_]*$"   

You can use this regex: 你可以使用这个正则表达式:

^(?!_)\w*(?<!_)$

\\w is equivalent to [A-Za-z0-9_] \\w相当于[A-Za-z0-9_]

I use negative look ahead (?!) to check the first character is not _ , and negative look-behind (?<!) to check the last character is not _ . 我使用负向前看(?!)来检查第一个字符是不是_ ,而负面后视(?<!)来检查最后一个字符是不是_

Specify an optional end with your criteria. 使用您的条件指定可选的结尾。

'^([a-zA-Z0-9]([a-zA-Z0-9_]*[a-zA-Z0-9])?)?$'

The outer parentheses are to permit an empty string, like your original attempt. 外括号是允许空字符串,就像你原来的尝试一样。 If you do not wish to match an empty string, you can simplify by removing the beginning parenthesis, and the closing parenthesis with a question mark quantifier. 如果您不希望匹配空字符串,可以通过删除开头括号和带有问号量词的右括号来简化。

Also note that I have used capturing parentheses for simplicity; 另请注意,为了简单起见,我使用了捕获括号; converting the opening parentheses to non-capturing (?: will supposedly also make it go a little faster, although in this simple case, it can hardly matter. 将开括号转换为非捕捉(?:据说也会使它更快一点,尽管在这个简单的情况下,它几乎不重要。

As suggested by @JoelCornett, you can use re.match to explicitly search only at the start if the string and drop the ^ anchor. 正如@JoelCornett所建议的那样,你可以使用re.match只在字符串的开头显式搜索字符串并删除^锚点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM