Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spacing being messed up in regular expression

Tags:

regex

I have the following regular expression

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

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

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

The string I'm testing it on is

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

which it properly matches. However, the issue I'm having is that when I write it out to the file, the spacing isn't preserved next to the equals sign so I end up with

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

It's a very minor difference but I'd appreciate feedback on how to improve the expression further to prevent this.

Here is a link to the regex!

I believe its an issue specifically with [\@A-Za-z1-9_\.\s\+\-\*\\]*

like image 622
Zee Avatar asked Aug 11 '15 18:08

Zee


2 Answers

Made it non-greedy match on space before =.

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

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

like image 68
lintmouse Avatar answered Oct 23 '22 09:10

lintmouse


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

                                                 ^^

You will have to ask previous group to not consume that space .See demo.

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

or if you have lookbehind use

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

                                                 ^^

See demo.

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

like image 36
vks Avatar answered Oct 23 '22 11:10

vks