Sachin
Sachin

Reputation: 1309

How do i match the character succeeding a particular string?

Currently i am using a perl regex where as a first preference i am intending to match the character ( number or alphanumeric ) immediately succeeding the string "Lecture" else match the last character in absence of string "Lecture" from each line .But it doesnt seem to work very well for my use case. i am adding my whole command below

cat 1.txt | perl -ne 'print "$1 \n" while /(?:\w*Lecture)?([^\s]+)$/g;'

Note - it might occur that there is no space around the string "Lecture" and the line might not end as .mp4 necessarily

cat 1.txt

54282068 Lecture74- AS 29 Question.mp4   
174424104Lecture 74B - AS 29 Theory.mp4   
Branch Accounts Lecture 105
Lecture05 - Practicals AS 28
Submissions 20.mp4
HW Section 77N

Expected output

74
74B
105
05
20
77N 

I preferably want a solution which I can directly run in the Cli/Console. ( Just Like my original code - cat 1.txt | perl code ). I don't want to execute a separate .pl file.

Upvotes: 0

Views: 203

Answers (1)

The fourth bird
The fourth bird

Reputation: 163352

You could use an alternation | matching either Lecture followed by optional horizontal whitespace chars or assert that Lecture is not present using a negative lookahead.

Lecture\h*\K\w+|^(?!.*Lecture).*\h\K[^.\s]+
  • Lecture\h* Match Lecture and optional horizontal whitespace chars
  • \K\w+ Clear the match buffer and match 1+ word chars
  • | Or
  • ^(?!.*Lecture) Assert that Lecture is not present
  • .*\h Match till the last horizontal whitespace
  • \K[^.\s]+ Clear the match buffer and match 1+ times any char except a whitespace char or a dot

Regex demo

Using \K you can get the match in this example instead of the capturing group.

For example

cat 1.txt | perl -ne 'print "$& \n" while /Lecture\h*\K\w+|^(?!.*Lecture).*\h\K[^.\s]+/g;'

Output

74
74B
105
05
20
77N

Upvotes: 2

Related Questions