Perl, Any match string after a pattern
Question
I'm trying to match if any string exists after a certain pattern. The pattern is "pattern" 'anything in between' "[after]". case insensitive.
e.g
pattern 1 [after] ABC
pattern 2 [after] 123 abc DEX
pattern 3 [after]
pattern 12345123 [after]
pattern @ASd#98 @_90sd [after] xyz dec
[after] 4 pattern
So the result I would like to obtain is,
pattern 1 [after] ABC
pattern 2 [after] 123 abc DEX
pattern @ASd#98 @_90sd [after] xyz dec
It begins with "pattern" and ends with "[after], anything sandwiched between is also accepted.
I'm having difficulty incorporating the delimits of [ ] & if string exists together.
I've tried, the closest I've gotten ends up matching
m/pattern/ ../ \[after]/
pattern 1 [after] ABC
pattern 2 [after] 123 ABC DEX
pattern 3 [after]
pattern 12345123 [after]
pattern @ASd#98 @_90sd [after] xyz dec
But I don't need the 3rd or 4th pattern as it doesn't hold any numerics or characters after "[after]".
Thanks
Solution
Here is the code I used to test against your input (which I just cat'ed and piped to the script)
#!/usr/bin/perl
while(<>)
{
print if (/^pattern.*\[after\]\s*\S+/);
}
So to break it down for you:
/^pattern
: match any string that begins with "pattern"
.*\[after\]
: match any characters followed by "[after]"
\s*\S+
: match 0 or more whitespace characters followed by one or more non-whitespace character
That should give you enough to work with to tweak it up as you see fit.
OTHER TIPS
Code:
$str = 'pattern 2 [after] 123 abc DEX';
if ($str =~ m/^pattern\s+(\d+)\s+\[after\]\s+(.+)/) {
print "$1\t$2\n";
} else {
print "(no match)\n";
}
Output:
2 123 abc DEX
Test this code here.
Is this what you want:
/pattern [0-9] \[after\](?= .)/s
or
/pattern [0-9] \[after\] ./s