4 ms·
I sometimes think regular expressions being greedy is a bad default.
by oweiler 4y ago
I sometimes think regular expressions being greedy is a bad default.
- matsemann 4y agoYeah, almost never what I want. Like if I have some "unstructured" data like a="xxx" b="yyy" And I do a regex like /a="(.*)"/ I'd like it to match xxx, not until the end " after yyy. Always have to do weird tricks like /a="([^"]*)"/
- PenguinCoder 4y agoTry `a="(.*?)\b"` next time. Where `\b` means a boundary such as the space in your example. Or use a more precise match for the capture group rather than the wildcard meaning ANYTHING.
- Joker_vD 4y agoAh, the /"([^"]*)"/ trick. It was one of those small, obvious in retrospect but not that easy to invent on your own, useful things I was taught at my first job among others such as "if in a unit test you need a future date, use year 3001".
- matsemann 4y agoYeah, in my toy example here I could probably go with a non-greedy modifier like .*?, but sometimes one needs to bring out these weird tricks, heh.
- adql 4y ago(sometimes) Bad for performance, probably what is expected for usability.
- klyrs 4y agoYou would have the same performance issue if the default was the opposite of greedy.