I have below sample string
abc,com;def,med;ghi,com;jkl,med
I have to grep the string which is coming before keyword ",com" (all occurrences)
Final result which is I am looking for is something like -
abc,ghi
I have tried below positive lookahead regex -
[\s\S]*?(?=com)
But this is only fetching abc, not the ghi.
What modification do I need to make in above regex?
Using a character class
[\s\S]can match any character and will also match the,and;What you can do is match non whitespace characters except for
,and;using a negated character class and that way you don't have to make it non greedy as well.Then assert the
,comto the right (followed by a word boundary to prevent a partial word match)Instead of using a lookahead, you might also use a capture group:
See a regex demo with the capture group values.