
[英]How to get the string which is starting after front slash in Perl regex?
[英]Perl regex: look for keyword which are not starting with
示例1: "hello this is me. KEYWORD: blah"
示例2: "KEYWORD: apple"
我只希望能够捕获示例1中的KEYWORD
,而不是2,因为在2中,它以KEYWORD
开头
if ($line =~/KEYWORD:/x) {
# do something
}
上面的代码捕获了两个示例。 如何更改正则表达式,使其仅捕获示例1中的KEYWORD
?
PS最后,我希望示例1成为KEYWORD: blah
您正在寻找一个否定的后置断言 ,即,对于没有特定字符串(在您的情况下为行首标记^
)开头的“ KEYWORD”:
if ($line =~/(?<!^)KEYWORD:/x) {
# found KEYWORD in '$line', but not at the beginning
print $line, "\n";
}
输出:
hello this is me. KEYWORD: blah
更新:如评论中所述, /x
修饰符在我的第一个正则表达式中不是必需的,但可用于使该模式更具可读性。 它允许在模式中使用空格(包括换行符)和/或注释以提高可读性。 缺点是实际模式中的每个空格/空格字符都必须转义(以将其与注释区分开),但是这里没有这些。 因此,可以按以下方式重写该模式(结果是相同的):
if ($line =~ / (?<! # huh? (?) ahh, look left (<) for something
# NOT (!) appearing on the left.
^) # oh, ok, I got it, there must be no '^' on the left
KEYWORD: # but the string 'KEYWORD:' should come then
/x ) {
# found KEYWORD in '$line', but not at the beginning
print $line, "\n";
}
答案实际上很简单!
/.KEYWORD/ # Not at the start of a line
/.KEYWORD/s # Not at the start of the string
顺便说一句,您可能希望在KEYWORD
之前添加\\b
以避免匹配NOTTHEKEYWORD
。
我认为您需要提供更好的真实示例
从表面上看,您所需要做的就是
if ( /KEYWORD/ and not /^KEYWORD/ ) {
...
}
另一个简单的正则表达式
print if /^.+KEYWORD/;
比赛
hello this is me. KEYWORD: blah
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.