Search code examples
regexregex-lookaroundsregex-negationregex-greedy

Need help to get only first match in regex with multiple matches


I have having a text output something like:

Principal Core Te1/1/0:
  DS 0 controller: 1/0/2  (profile 200, DOCSIS)
  DS 1 controller: NA
  US 0 controller: 1/0/0  (profile 0, DOCSIS)
  US 1 controller: NA
  Mac Domain: Ca1/0/0

Auxiliary Core Te1/1/6:
  DS 0 controller: NA
  DS 1 controller: NA
  US 0 controller: NA
  US 1 controller: NA
  Mac Domain: NA

I want to match a regex with matched the mac domain of the principle core. I tried various Regular expressions but failing. My Regexs are always capturing the 2nd mac domain which is N/A. Is there any way I can get regex for Mac Domain: followed by Principle Core.

Update:

Constraints:- Only gm can be used as flags in the regex. Language: javascript


Solution

  • My guess is that you just have a greedy vs. lazy dot problem here. The following regex pattern, with dot all mode enabled, is working:

    Principal Core.*?\bMac Domain: (\S+)
    

    Demo

    The Mac domain would then be available in the first capture group. The exact code you would use depends on the language/tool you are using, but the above general pattern is at least a good start.

    Edit:

    If your regex engine does not have a dot all mode, we can simulate that by matching on [\s\S]* instead of .*:

    Principal Core[\s\S]*?\bMac Domain: (\S+)