Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace dot notation by brackets in query string

Tags:

regex

Basically I'm trying to replace this: a.b.c=17.5.2017&x.y=z

with this: a[b][c]=17.5.2017&x[y]=z

I have found a regular expression online a while ago, it looks like this:

[.]([^.]*?)(?=[=.&]|$)

Now, this works, but it also replaces values in the query string. Meaning in my original example, the date (17.5.2017) gets replaced by 17[5][2017], see here:

https://regex101.com/r/5IzNov/1/

What I am thinking of would be to only match if there was not the = symbol before the & symbol or it's the beginning of the string. However I have no idea how to do this. I assume I will need a conditional lookbehind, but that's way beyond my knowledge.

like image 533
marekpw Avatar asked Jun 08 '26 19:06

marekpw


1 Answers

You can search using this regex:

[.]([^.&=]+)(?=[^=&]*=)

And replace using:

[$1]

RegEx BreakUp:

  • [.] - Match a literal DOT
  • ([^.&=]+) - Match 1 or more of characters that are not one of[.&=]
  • (?=[^=&]*=) - Lookahead to assert we have a = ahead without encountering &

Updated RegEx Demo

like image 175
anubhava Avatar answered Jun 10 '26 09:06

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!