Interval messed up in regex

I have the following regex

var string_regex=(\s*[\{\[]?\%?[\s]*)[\@A-Za-z1-9_\.\s\+\-\*\\]*([\s\*]*=[\s\*\$]*[\{\"]?)[\@A-Za-z1-9_\.\s\+\-\*\\]*(\s*[\}\"]?)([\}\]\%\s]*) 

where [\@A-Za-z1-9_\.\s\+\-\*\\]* will eventually be replaced by a line in my program, which will be written to a file that uses $1, $2, $3 and $4 as follows:

 val newLineToBeReplacedOrAdded = "$1" + "set type cookies" + "$2" + "sugar cookies" + "$3" + "$4" 

The line I'm testing is

 {% set type cookies = "sugar cookies" %} 

which it matches correctly. However, the problem that I am facing is that when I write it to a file, the interval is not saved next to the equal icon, so I get

 {% set type cookies= "sugar cookies" %} 

This is a very minor difference, but I will be grateful for the feedback on how to improve the expression in order to prevent this.

Here is the regex link!

I believe this is a problem with [\@A-Za-z1-9_\.\s\+\-\*\\]*

+5
source share
2 answers

Made it not a greedy coincidence in space before =.

 [\@A-Za-z1-9_\.\s\+\-\*\\]*? 

https://regex101.com/r/yN4mX0/3

+3
source
 (\s*[\{\[]?\%?[\s]*)[\@A-Za-z1-9_\.\s\+\-\*\\]*[^\s]([\s\*]*=[\s\*\$]*[\{\"]?)[\@A-Za-z1-9_\.\s\+\-\*\\]*(\s*[\}\"]?)([\}\]\%\s]*) ^^ 

You will need to ask the previous group not to use this space. See the demo.

https://regex101.com/r/yN4mX0/2

or if you have lookbehind used

 (\s*[\{\[]?\%?[\s]*)[\@A-Za-z1-9_\.\s\+\-\*\\]*(?<!\s)([\s\*]*=[\s\*\$]*[\{\"]?)[\@A-Za-z1-9_\.\s\+\-\*\\]*(\s*[\}\"]?)([\}\]\%\s]*) ^^ 

See the demo.

https://regex101.com/r/yN4mX0/4

+3
source

All Articles