RegExp 匹配字符串不以 my 开头
对于 PMD,我希望有一个规则来警告我那些以 my
开头的丑陋变量。
这意味着我必须接受所有不以my
开头的变量。
所以,我需要一个正则表达式(re),其行为如下:
re.match('myVar') == false
re.match('manager') == true
re.match('thisIsMyVar') == true
re.match('myOtherVar') == false
re.match('stuff') == true
我已经尝试了不同的,但还没有让它工作。
For PMD I'd like to have a rule which warns me of those ugly variables which start with my
.
This means I have to accept all variables which do NOT start with my
.
So, I need a RegEx (re) which behaves as follows:
re.match('myVar') == false
re.match('manager') == true
re.match('thisIsMyVar') == true
re.match('myOtherVar') == false
re.match('stuff') == true
I've tried different ones but haven't got it working yet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
应该有效。
它首先确保不可能在字符串开头匹配
my
,然后匹配字母数字字符,直到字符串末尾。字符串中任何位置的空格都会导致正则表达式失败。根据您的输入,您可能需要在将字符串传递给正则表达式之前去除字符串前后的空格,或者使用向正则表达式添加可选的空格匹配器,例如^\s*(?!my)(\ w+)\s*$
。在这种情况下,反向引用 1 将包含变量的名称。如果您需要确保变量名称以特定字符组开头,例如
[A-Za-z_]
,请使用注意从
+
到的更改>*。
should work.
It first ensures that it's not possible to match
my
at the start of the string, and then matches alphanumeric characters until the end of the string. Whitespace anywhere in the string will cause the regex to fail. Depending on your input you might want to either strip whitespace in the front and back of the string before passing it to the regex, or use add optional whitespace matchers to the regex like^\s*(?!my)(\w+)\s*$
. In this case, backreference 1 will contain the name of the variable.And if you need to ensure that your variable name starts with a certain group of characters, say
[A-Za-z_]
, useNote the change from
+
to*
.(?!expression)
是一个否定的前瞻;它匹配表达式
不从该位置开始匹配的位置。(?!expression)
is a negative lookahead; it matches a position whereexpression
doesn't match starting at that position.您可以像其他人建议的那样使用前瞻断言。或者,如果您只想使用基本的正则表达式语法:
这会匹配零个或一个字符长 (
^.?$
) 的字符串,因此不能是my
。或者包含两个或多个字符的字符串,其中当第一个字符不是m
时,后面可以有更多字符 (^[^m].+
);或者,如果第一个字符是m
,则后面不能跟y
(^m[^y]
)。You could either use a lookahead assertion like others have suggested. Or, if you just want to use basic regular expression syntax:
This matches strings that are either zero or one characters long (
^.?$
) and thus can not bemy
. Or strings with two or more characters where when the first character is not anm
any more characters may follow (^[^m].+
); or if the first character is am
it must not be followed by ay
(^m[^y]
).进行正匹配并拒绝这些字符串,而不是匹配负匹配来查找要接受的字符串,这不是更具可读性吗?
Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?