3 ms·
In Java I prefer to do something like this: "[(),]" // match the foo part... + "|\"(?:\\.|[^\"\n])*\"" //... or, match the bar part in *double* quotes, put
by TeMPOraL 11y ago
In Java I prefer to do something like this:
"[(),]" // match the foo part...
+ "|\"(?:\\.|[^\"\n])*\"" //... or, match the bar part in *double* quotes, putting quoted value in capture group 1...
+ "|'(?:\\.|[^'\\n])*'" //... or, match the bar part in *single* quotes, putting quoted value in capture group 1...
+ "|\/\*[\s\S]*?\*\" //... or, match whatever the hell that is.
Simple string splitting + commenting the semantic parts. Also, labeling the capture group (and creating named constants for them in your code next to your regex) is a huge win.
- pygy_ 11y agoIf the string you happen to match contains a lot of metacharacters, you end up with backslashes all over the place, which makes the result hard to read. Nested groups and captures are also often hard to parse. FWIW, you forgot to double escape `\\\\.`, and didn't close the CSS comment (last alternative). "[(),]" // match the foo part... + "|\"(?:\\\\.|[^\"\\n])*\"" //... or, match the bar part in *double* quotes + "|'(?:\\\\.|[^'\\n])*'" //... or, match the bar part in *single* quotes + "|\/\*[\s\S]*?\*\/" // or match the comment Also, you're probably not familiar with the quirks of JS regexps, but the two string alternatives use non-capturing groups, and `[\s\S]` is the true "any" matcher, `.` doesn't match new lines. At last, `*?` is a non-greedy `*`. (Edited thrice, damn you italics).
- TeMPOraL 11y agoThanks for the clarifications! I admit I just copied your example and tried to sort-of convert it into Java style. It definitely won't be a correct Java-compatibile regex. As you said, I'm not familiar with the JS regex quirks. I just couldn't invent a good example on the spot, and didn't want to post ones from the code I work on at my day job for legal reasons. And yeah, I agree about "lots of backslashes" part. It gets messy - but splitting regexps in parts makes it at least more manageable. I'm not yet angry enough at the cases I have at my day job to whip up a DSL for it though.