These are some demo strings,
enum('a', 'b', 'c')
varchar(255)
int unsigned
Taking first one as an example, I want to match enum
and 'a', 'b', 'c'
. Everything inside brackets are optional as you see in 3rd example: int unsigned
. How do I do this?
I tried,
(.*)(\((.*)\))?
However this matches whole string for some reason.
const out = /(.*)(\((.*)\))?/.exec(`enum('a', 'b', 'c')`)
console.log(out)
CodePudding user response:
You can use
const [, first, second] = /^(.*?)(?:\((.*)\))?$/.exec(`enum('a', 'b', 'c')`)
console.log(first '\n' second)
See the regex demo. Details:
^
- start of string(.*?)
- Group 1: any zero or more chars other than line break chars as few as possible(?:\((.*)\))?
- an optional sequence of(
, any zero or more chars other than line break chars as many as possible (captured into Group 2), and then a)
char$
- end of string.
CodePudding user response:
const tests = [
"enum('a', 'b', 'c')",
"varchar(255)",
"int unsigned"
];
tests.forEach(test => console.log(/([^(] )(?:\((.*)\))?/.exec(test)));
The first capturing group grabs the part before the parenthesis, the second optionally what is contained within the parenthesis if applicable.