Regex to match first occurence of a string starting and ending with predefined characters

136 Views Asked by At

I'm trying to match the first occurence for the company name: EuroPayment Services S.R.L. I tried to make it non-greedy by adding ? but without success. What am I doing wrong?

  Name:          EuroPayment Services S.R.L.
  Address:         Str. Ion Cămpineanu, nr. 11, Bloc Union, etaj 8, camera 803
  Name:          General Motors S.R.L.
  Address:         Str. Ion Cămpineanu, nr. 11, Bloc Union, etaj 8, camera 803

Also, how can I match the second occurence of the company name? General Motors S.R.L

Demo

1

There are 1 best solutions below

4
Niel Godfrey Pablo Ponciano On BEST ANSWER

Regex to capture the first name:

Name:\s+(.*)[\s\S]*

Sample run here.

You can also capture the nth-name through this (just update the 0-based index part {n} to your target e.g. {4} to get the 5th name:

  • name 1: (?:Name:[\s\S]+?){0}Name:\s+(.*)[\s\S]*
  • name 2: (?:Name:[\s\S]+?){1}Name:\s+(.*)[\s\S]*
  • name 3: (?:Name:[\s\S]+?){2}Name:\s+(.*)[\s\S]*
  • name 4: (?:Name:[\s\S]+?){3}Name:\s+(.*)[\s\S]*
  • and so on...