我有一个与regex匹配的字符串,但同一个字符串前面用#号注释掉了,regex一直与它匹配,这是我不希望的。
我的Regex
BLTY:w{8}:w{8}:w{5}.w{7}.w{1}.w{3}/w{3}/.*(w{4})
字符串
BLTY:ENCQ0000:SERVER:TEMP.PPMQ8FE.Y.323/TCP/gtg23.dev.pmt.com(3213)-> only match this
#BLTY:ENCQ0000:SERVER:TEMP.PPMQ8FE.Y.323/TCP/gtg23.dev.pmt.com(3213) -> I dont want to match this
尝试
^[BLTY:w{8}:w{8}:w{5}.w{7}.w{1}.w{3}/w{3}/.*(w{4})]
^BLTY:w{8}:w{8}:w{5}.w{7}.w{1}.w{3}/w{3}/.*(w{4})
(?!#)BLTY:w{8}:w{8}:w{5}.w{7}.w{1}.w{3}/w{3}/.*(w{4})
此外,如果有一种不那么冗长/优化的方式来编写这个正则表达式,我愿意听取
无需使用lookahead:
^BLTY(?::w+){3}(?:.w+){3}/.*(d+)$
请参阅正则表达式证明。
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
BLTY 'BLTY'
--------------------------------------------------------------------------------
(?: group, but do not capture (3 times):
--------------------------------------------------------------------------------
: ':'
--------------------------------------------------------------------------------
w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
){3} end of grouping
--------------------------------------------------------------------------------
(?: group, but do not capture (3 times):
--------------------------------------------------------------------------------
. '.'
--------------------------------------------------------------------------------
w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
){3} end of grouping
--------------------------------------------------------------------------------
/ '/'
--------------------------------------------------------------------------------
.* any character except n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
( '('
--------------------------------------------------------------------------------
d+ digits (0-9) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
) ')'
--------------------------------------------------------------------------------
$ before an optional n, and the end of the
string