1

Im using this regex online test site.

Here is the regex im using:

\{"ip":"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$","iphone":"admin/ios","dev":\{"action":"CUS","from":"REG","CUSA":"ADVERT"\}\}

And im trying to match it to:

{"ip":"192.168.50.5","iphone":"admin/ios","dev":{"action":"CUS","from":"REG","CUSA":"ADVERT"}}

When i run the test, it doesn't match, I need it to match on the site above for validation reasons.

Gurmukh Singh
  • 1,875
  • 3
  • 24
  • 62

2 Answers2

2

A different perspective: it seems that it is already pretty hard to come up with a regex that initially works for you. What does this tell you about how hard will it be in the future to maintain this regex; and maybe extend it?!

What I am saying is: regexes are a good tool; but sometimes overrated. This looks like a string in JSON format. Wouldn't it be better to just take it as that, and use a garden-variety JSON parser instead of trying to build your own regex?

You see, what will be more robust over time - your self baked regex; or some standard library that millions of people are using?

One place to read about JSON parsers would be this question here.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
-2

This will be enough for your context.

"ip":"(\d+).(\d+).(\d+).(\d+)"

Edit:

Regex is not for structured data processing, most of the time you need a solution that just works. When sample data changed and doesn't match anymore, you update the regex string to match it again.

Since you want to get four numbers inside a quote pair after a key called "ip", this regex will definitely do it.

If you want something else, please provide more context. Thanks!

Henry.T
  • 135
  • 2
  • 9
  • 1
    The IP is only one part of this code; and you seriously want to read about IP addresses. Your regex is absolutely not sufficient to go hunting for ip addresses. Yes, first reputation is hard to gain; but well - you have to invest much more time to come up with quality answers! – GhostCat Aug 02 '16 at 10:45
  • Although this code may help to solve the problem, providing additional context regarding _why_ and/or _how_ it answers the question would significantly improve its long-term value. Please [edit] your answer to add explanation, including what limitations and assumptions apply. – Toby Speight Aug 02 '16 at 14:22