Home > other >  How to match a wildcard for strings?
How to match a wildcard for strings?

Time:03-14

Please suggest a wildcard for below Firstjson list

Firstjson = { p10_7_8 , p10_7_2 , p10_7_3 p10_7_4}

I have tried p10.7.* wildcard for below Secondjson list, it worked. But when I tried p10_7_* for above Firstjson list it did not work

Secondjson = { p10.7.8 , p10.7.2 , p10.7.3 , p10.7.4 }

CodePudding user response:

You are attempting to use wildcard syntax, but Groovy expects regular expression syntax for its pattern matching.

What went wrong with your attempt:

Attempt #1: p10.7.*

A regular expression of . matches any single character and .* matches 0 or more characters. This means:

p10{exactly one character of any kind here}7{zero or more characters of any kind here}

You didn't realize it, but the . character in your first attempt was acting like a single-character wildcard too. This might match with p10x7abcdefg for example. It also does match p10.7.8 though. But be careful, it also matches p10.78, because the .* expression at the end of your pattern will happily match any sequence of characters, thus any and all characters following p10.7 are accepted.

Attempt #2: p10_7_*

_ matches only a literal underscore. But _* means to match zero or more underscores. It does not mean to match characters of any kind. So p10_7_* matches things like p10_7_______. Literally:

p10_7{zero or more underscores here}

What you can do instead:

You probably want a regular expression like p10_7_\d

This will match things like p10_7_3 or p10_7_422. It works by matching the literal text p10_7_ followed by one or more digits where a digit is 0 through 9. \d matches any digit, and means to match one or more of the preceding thing. Literally:

p10_7_{one or more digits here}

  • Related