Pages

Thursday, December 20, 2018

regex Patterns

Lookbehind Regex 

Normally we can grep will search for a word and prints the entire line which has the match word. 

Using -O option we can print only the matching word.

If we want to search a word and print the word next to it. then we need to use Look behind in regex.

Syntax for Look Behind is enter the match word between the parenthesed followed by ? and <. Add = if you want to do positive lookbehind or add ! if you want to do negative lookbehind. Something like -v in grep option.

(?<=matchword)\w*
       
Examples 
1) Lookbehind

[test@localhost ]# echo "Input : File Java.lanag.xyz..File 
copied completed : one.txt" | grep -oP '(?<=File copied 
completed : 
)\w*.*' 
Output : one.txt
) Lookahead
[test@localhost ~]# echo "Input : File 
:Java.lanag.xyz..File copied completed : one.txt" | grep 
-oP '\w*(?= : \w*.txt)'
completed
[root@localhost log]#
3) Both
Input Text: applebananabananaapple 
(i)  banana(?=banana) - finds the 1st test ("banana" which 
has "banana" after it) 
(ii) banana(?!banana) - finds the 2nd test ("banana" which 
does not have "banana" after it)

(iii) (?<=apple)banana- finds the 1st test ("banana" which 
has "apple" before it)
(iv) (?<!apple)banana- finds the 2nd test ("banana" which 
does not have"apple" before it)      


No comments:

Post a Comment