1

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?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Abhishek
  • 41
  • 5

1 Answers1

3

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 ,com to 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:

([^\s,;]+),com\b

See a regex demo with the capture group values.

The fourth bird
  • 154,723
  • 16
  • 55
  • 70