javascript - Regex with optional prefix - Stack Overflow

admin2025-04-08  1

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.

Share Improve this question asked Mar 12, 2018 at 14:08 webdevverbewebdevverbe 271 silver badge8 bronze badges 4
  • what can be the prefix ? – moghya Commented Mar 12, 2018 at 14:11
  • Your original regex doesn't do what you say it does. i.e. split 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
  • Try (abc\.)?(\w+)(?:\[[^\]]*\])? – ctwheels Commented Mar 12, 2018 at 14:15
Add a ment  | 

2 Answers 2

Reset to default 6

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'
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744124630a232408.html

最新回复(0)