Happydevdays
Happydevdays

Reputation: 2072

can't seem to get right php regex quantifier

I have a string that looks like this:

msg": "log domain jl.lab.test.net server lab-jl-ppr-web"

I'm trying to extract "jl.lab.test.net" and JUST "lab-jl-ppr" from "lab-jl-ppr-web" using the following regular expression:

 preg_match("/\"msg\"\: \"log domain\s([\w*\.]*) server ([\w*\.\-]*)/i",$line,$matches);

The second group currently matches the entire "lab-jl-ppr-web" string. I have been trying to specify the proper quantifier but so far I haven't gotten the right one. I've tried the following:

 preg_match("/\"msg\"\: \"log domain\s([\w*\.]*) server ([\w*\.\-]*){3}/i",$line,$matches);

I'm continuing to play with it but if you have any tips, i'd appreciate it. Thanks.

Upvotes: 0

Views: 44

Answers (4)

user557597
user557597

Reputation:

This probably works

'~"msg":[ ]"log[ ]domain\s([\w.]*)[ ]server[ ]((?:(?!-web)[\w.-])*)~'  

but, it's hard to get what you're looking for from the regex.

Expanded

 "msg": [ ] "log [ ] domain \s 
 ( [\w.]* )                    # (1)
 [ ] server [ ] 
 (                             # (2 start)
      (?:
           (?! -web )
           [\w.-] 
      )*
 )                             # (2 end)

Output

 **  Grp 0 -  ( pos 0 , len 52 ) 
"msg": "log domain jl.lab.test.net server lab-jl-ppr  
 **  Grp 1 -  ( pos 19 , len 15 ) 
jl.lab.test.net  
 **  Grp 2 -  ( pos 42 , len 10 ) 
lab-jl-ppr  

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use the following approach with preg_match_all function:

$str = "log domain jl.lab.test.net server lab-jl-ppr-web";
preg_match_all("/\b\w+\.\w+\.\w+\.\w+\b|\b\w+-\w+-\w+(?=-\w+?)\b/U", $str, $matches);

print_r($matches[0]);

The output:

Array
(
    [0] => jl.lab.test.net
    [1] => lab-jl-ppr
)

Upvotes: 0

That one seems legit but i'm sure better one can be written.

^log domain ([a-zA-Z\.]+) server ([a-zA-Z\.\-]+)-web$

Here you can test it

LiveRegex

Upvotes: 0

Marc B
Marc B

Reputation: 360592

Why not just

/..snip.. server ([\w*\.\-]*)-web/i

? Just keep -web outside of the capture group.

Upvotes: 1

Related Questions