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\+\-\*\\]*
Made it non-greedy match on space before =.
[\@A-Za-z1-9_\.\s\+\-\*\\]*?
https://regex101.com/r/yN4mX0/3
(\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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With