I'm not really confortable with regexes but need to extend a legacy one. Currently we are having this regex in our application:
const regex = /([a-zA-Z0-9_]+)(?:\[(.*?)\])?/g;
This allows us to split strings like this:
hello[foo='bar']
Into:
hello and [foo='bar']
But due to a recent update, the 'hello'-part can also contain a prefix named 'abc.'. The result would be abc.hello[foo='bar']. However this is optional.
With the current regex we are having this will split into an array that only contains ['abc', 'abc', undefined]
If someone could help me add this optional prefix to the current regex that would be highly appreciated.
I'm not really confortable with regexes but need to extend a legacy one. Currently we are having this regex in our application:
const regex = /([a-zA-Z0-9_]+)(?:\[(.*?)\])?/g;
This allows us to split strings like this:
hello[foo='bar']
Into:
hello and [foo='bar']
But due to a recent update, the 'hello'-part can also contain a prefix named 'abc.'. The result would be abc.hello[foo='bar']. However this is optional.
With the current regex we are having this will split into an array that only contains ['abc', 'abc', undefined]
If someone could help me add this optional prefix to the current regex that would be highly appreciated.
hello[foo='bar']
to hello and [foo='bar']
– gurvinder372
Commented
Mar 12, 2018 at 14:11
/(abc\.)?([a-zA-Z0-9_]+)(?:\[(.*?)\])?/g;
– standby954
Commented
Mar 12, 2018 at 14:12
(abc\.)?(\w+)(?:\[[^\]]*\])?
– ctwheels
Commented
Mar 12, 2018 at 14:15
You can simply prepend (abc\.)?
to your regex, but I'd also make a slight adjustment as defined below:
(abc\.)?(\w+)(\[[^\]]*\])?
(abc\.)?
Optionally captures abc.
into capture group 1(\w+)
Captures one or more word characters into capture group 2. \w
is shothand for [a-zA-Z0-9_]
(?:\[[^\]]*\])?
Optionally capture the following into capture group 3
\[
Matches [
literally[^\]]*
Matches any character except ]
any number of times. This is better than using .*?
since it doesn't backtrack. This means better performance.\]
Matches ]
literally
var a = ["abc.hello[foo='bar']", "hello[foo='bar']"]
var r = /(abc\.)?(\w+)(\[[^\]]*\])?/
a.forEach(function(s) {
console.log(s.match(r))
})
Should work by just adding the dot to the first group in your regex:
([a-zA-Z0-9_.]+)(?:\[(.*?)\])?
That would split
abc.hello[foo='bar']
into
abc.hello
and
foo='bar'
and also
hello[foo='bar']
into
hello
and
foo='bar'