ealeon ealeon - 1 year ago 59
Perl Question

Perl regex: look for keyword which are not starting with

Example 1:

"hello this is me. KEYWORD: blah"

Example 2:
"KEYWORD: apple"

I just want to be able to catch
in example 1, not 2 since in 2, it starts with

if ($line =~/KEYWORD:/x) {
# do something

The above code catch both examples. How can I change regex so that it only catches
in example 1?

PS Eventually I want example 1 to be

Answer Source

If you are just looking for a keyword, you should be using index and not a regex :

if (index($line, 'KEYWORD') > 0) {
    # do something

See the documentation : index STR, SUBSTR returns -1 if SUBSTR isn't found in STR, otherwise it return the index of SUBSTR in STR (starting at 0).

If you want to look for a more complex pattern than a simple keyword, then you should do as @Perl Dog said in his answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download