8 ms·
ECMAScript regular expressions are getting better (2017)
- hidiegomariani 8y agofinally named capture groups
- dclowd9901 8y agoFinally lookbehind!!!
- sertsetrert 8y agothe two philosophies
- JadeNB 8y agoThere's a difference, right, in that named capture groups are purely cosmetic, whereas look-behind can dramatically slow down matching? (I dunno in any theoretical sense, but that's the way it goes in Perl.)
- DFHippie 8y agoNamed captures means you don't have to count parentheses to figure out which group you want. I don't know whether it qualifies as cosmetic, but it sure is nice.
- JadeNB 8y ago> Named captures means you don't have to count parentheses to figure out which group you want. I don't know whether it qualifies as cosmetic, but it sure is nice. Agreed! (As a regex-heavy Perl hacker, I loved the day that they entered the language.) I didn't mean to minimise them; rather quite the opposite, to point out that they gave a great return essentially for free (compared to regexes that still have capturing groups, but without names), as opposed to look-behind, which (I think) can slow down a match dramatically.
- shawn 8y agoAnother proposal specifies certain legacy RegExp features, such as the RegExp.prototype.compile method and the static properties from RegExp.$1 to RegExp.$9. Although these features are deprecated, unfortunately they cannot be removed from the web platform without introducing compatibility issues. Thus, standardizing their behavior and getting engines to align their implementations is the best way forward. This proposal is important for web compatibility. Interesting view. Is this better than a "let it break" approach? Link rot already claims N% of websites per year. I wonder if cleaning up APIs like this one would increase N noticeably.
- dspillett 8y ago> Interesting view. Is this better than a "let it break" approach? Or perhaps a branch and let the old stagnate approach? Strip the deprecated features to create RegEx2/RegExNG/whatever[1] and build the new features on that. Old code can keep using the old version as they always have, new code can use all the nice new shinys, and the new version doesn't have to worry about backwards compatibility with the broken parts of dark age UAs. Also make sure everything in the new spec can be polyfilled for cases when new code needs to work on those older UAs. [1] or while we are branching off, why not answer the complaint of regexs usually not actually being regular (as per the mathematical concept of regular languages) and rename them completely? Maybe SearchExpressions? Or SearchExp if you want something smaller. Or SExp if you want even shorter and don't mind attracting bad puns.
- alangpierce 8y agoI think breaking JS tends to be much more destructive than dead links. At least with dead links there's a fairly clear non-technical fix. With a web standards break, maybe 8 years ago you hired a contractor to build a website that uses a library that uses a library that uses a library that uses some JS feature that is now broken, so your website is now completely broken. Some of those libraries are on older unmaintained versions, where the only upgrade would be through non-trivial breaking changes, or you would need to just find alternate libraries. Getting things working again is a huge undertaking, not just a matter of "don't use that weird JS feature anymore", and I think in that situation it seems reasonable to blame the browser for the breaking change. It's also maybe more widespread than you'd think. Adding `global` seemed safe for a long time, but ended up breaking both Flickr and Jira because they both use a library that broke: https://github.com/tc39/proposal-global/issues/20 https://github.com/tc39/proposal-global/issues/20
- kibwen 8y agoAside, but I'd love for someone to come up with an alternative syntax for regexes that sacrifices speed-of-typing for ease-of-reading. Regexes are obviously still fantastically useful for things like command-line scripting and jumping around in text editors, but the fact that people still reach for regexes within programs that are meant to receive long-term maintenance tells me that we're missing a tool in our toolbox.
- arkh 8y agoMost regexp libraries let you use named groups and comments which let you write more maintainable expressions. The fact javascript does not may explain why so many people don't know how to use them. https://www.regular-expressions.info/freespacing.html https://www.regular-expressions.info/freespacing.html https://www.regular-expressions.info/named.html https://www.regular-expressions.info/named.html
- gmac 8y agoYou can have some of this in JS too by using libraries such as this one (which is mine): https://github.com/jawj/js-xre https://github.com/jawj/js-xre
- tlarkworthy 8y agoIt does now! (named capture groups)
- chrissam 8y agoES2018 introduces named capture groups. They're available today in Chrome, unsure about other browsers.
- YorickPeterse 8y agoRosie (https://gitlab.com/rosie-pattern-language/rosie https://gitlab.com/rosie-pattern-language/rosie) is an interesting approach to this problem, and I think PEGs in general would be better for reading. My memory is a bit foggy on the details, but I do recall that PEGs have some problems parsing certain inputs performance wise, though I could be mistaken.
- dbrgn 8y agoIt's funny to see that in almost all langues the regular expression engines are not actually regular. This results in developers regularly (pun maybe intended) shooting themselves in the foot with overly clever expressions. (Notable exception: Rust https://docs.rs/regex/ https://docs.rs/regex/)
- burntsushi 8y agoThanks for the mention! I just want to expand on some things you said: - Rust's regex library was greatly inspired by RE2, which is a C++ library that also executes regexes in linear time. - Go's regex library also runs in linear time, however, it is still missing some optimizations that can make it run more slowly on non-pathological regexes when compared to RE2 and Rust's regex crate. - You don't need to use fancy features with a backtracking regex engine in order to shoot yourself in the foot. e.g., >>> import re >>> re.search('(a*)*c', 'a' * 30) - Even with linear time regex engines, you can get big slow downs. You'll never get exponential (in the size of the text) slow downs of course, but regexes like `[01]*1[01]{20}$`[1] can generate large finite state machines, which can be problematic in either memory or match speed, depending on the implementation. [1] - https://cyberzhg.github.io/toolbox/min_dfa?regex=KDB8MSkqMSgwfDEpKDB8MSkoMHwxKSgwfDEpKDB8MSkk https://cyberzhg.github.io/toolbox/min_dfa?regex=KDB8MSkqMSg...
- ridiculous_fish 8y agoDoes the linear time hold up in the face of capture groups? For example, say you have a bunch of capture groups in a loop: /((a)|(b)|(c)|(d))*/ If the string has length N, the loop iterates N times, and each iteration must clear capture groups proportional to the length of the regex. So in this case the time varies as the product of the input and regex length, not their sum independently.
- beagle3 8y agoFirst match, then capture. All captures are wasteful unless there’s a match.
- fock 8y agoI hope you don't need such things anymore then: https://github.com/sindresorhus/shebang-regex/blob/master/index.js https://github.com/sindresorhus/shebang-regex/blob/master/in...
- dclowd9901 8y ago‘matchAll’ looks great but why make it an iterator vs a ‘map’ style callback? Just seems so arcane.
- masklinn 8y ago> ‘matchAll’ looks great but why make it an iterator vs a ‘map’ style callback? Because that makes it significantly easier to e.g. optionally collect into an array, or to only partially iterate the sequence (e.g. only get the first 3 matches) which is painful to impossible using JS's callbacks. An iterator is simply more flexible.
- thomasfoster96 8y agoFor what it’s worth Array.from() [0] lets you pass a map style callback as its second argument, so Array.from(yourStr.matchAll(yourRegex), yourMapFn) works. [0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- deleted 8y ago[deleted]
- idbehold 8y agoThis article is nearly two years old. Not that this isn't a great article, but people should probably know that these features aren't entirely new.
- Lord_Zero 8y agoI am also curious about which the the proposed features actually made it, and which did not. - dotAll mode (the s flag) - Lookbehind assertions - Named capture groups - Unicode property escapes - String.prototype.matchAll - Legacy RegExp features
- mathias 8y agoI make sure to keep the article up-to-date. It correctly states the status for each of the features. They’re all part of ES2018 with the exception of String#matchAll which is currently at Stage 3.
- mathias 8y agoHey, I’m the author of the article. Despite its age, it’s still accurate and up-to-date. > these features aren't entirely new Depends on what you mean by that. These features are still not universally supported by all modern browsers, for example, so I can imagine they’re still new to a lot of developers. Chrome supports all these features (except for String#matchAll, which is currently at Stage 3). Other browsers don’t yet support the full set, but they’re all working on getting there.
- evanmarks 8y agoGoddess you can get iyfedcqxdddcsgdvddq z ccctggezryrdx bloTyne dw
- pier25 8y agoThis is cool, but I really wish the TC39 was more focused on solving major problems with the language instead of small incremental updates.
- interesthrow2 8y agoissues such as what?
- pier25 8y agoFor example, the lack of types.
- deleted 8y ago[deleted]
- JoelJacobson 8y agoJavascript regexes are "getting better" feature-wise, but performance-wise not much have improved. The the a?a?a? example regex in Ross Cox article "Regular Expression Matching Can Be Simple And Fast" from 2007 is still getting exponentially slower and slower with the number of "a?"-repetitions (https://swtch.com/~rsc/regexp/regexp1.html https://swtch.com/~rsc/regexp/regexp1.html) for (let i=20; i<30; i++) { let str = "a".repeat(i); let regex = new RegExp("a?".repeat(i) + "a".repeat(i)); let t0 = performance.now(); str.match(regex); let t1 = performance.now(); console.log(i + " took " + Math.round(t1 - t0) + " milliseconds."); } 20 took 7 milliseconds. 21 took 14 milliseconds. 22 took 27 milliseconds. 23 took 52 milliseconds. 24 took 102 milliseconds. 25 took 224 milliseconds. 26 took 421 milliseconds. 27 took 814 milliseconds. 28 took 1604 milliseconds. 29 took 3470 milliseconds. Tested today on latest Chrome on a MacBook Pro 2,6GHz Intel Core i7. Here comes an idea on what could be done to improve performance for regexes that are actually regular, and to still keep support for non-regular advanced regexes that e.g. contain back-references: Add a step immediately after parsing the regex, check if it is regular and can be handled by an engine like RE2, otherwise handle it using the normal regex engine. An even more exotic idea would be to let multiple regex engines execute in parallell, and return the result for the one that finishes first.
- tlb 8y agoUse repetition range matching for O(1) performance: /a{1,30}/ Can you give an example of a regex that can't be easily re-written to be fast with the backtracking engine?
- ehaliewicz2 8y agoThe point is, with the NFA approach, there are no regexes that exhibit catastrophic backtracking. So you can't shoot your foot with expressions that seem fine but send your cpu off into la-la land when asked to match certain input data.
- tlb 8y agoIt's a strange property to want. It's not a property of most other parts of programming languages. You can write loops or function calls in any language that take exponential time. So why demand that regexps be immune to it? It would make sense to worry about it if it were a common mistake, but I've never seen a gratuitously exponential regexp in the wild.
- jancsika 8y agoIs there a linter that can scan ECMAScript regex constants and disallow any that go beyond what is allowed in a regular language?
- ridiculous_fish 8y agoIs the idea to avoid catastrophic backtracking? Unfortunately you aren't immunized from catastrophic backtracking by limiting yourself to regular languages. The catastrophe is a property of the implementation, not the matched language.
- tobyhinloopen 8y agoI like the `matchAll` feature. I now use the awesome/awful (depending who you ask) hack using `.replace`: var matches = []; "12345678".replace(/\d/g, (m) => matches.push(m)); console.log(matches);
- nik1aa5 8y agoSince this is from 2017, isn't the year missing in the title? When I initially saw the submission, for a moment I thought all the struggles I had some weeks ago had been solved... :-)
- dang 8y agoGood catch. Added. Sorry. Thanks!
- mathias 8y agoI mean, they have been solved. With the exception of String#matchAll (which is currently a Stage 3 proposal), all these features are part of ES2018 and shipping in Chrome. Other browsers implement some of them already and are working on shipping more. You can view the implementation status of the various features here: https://kangax.github.io/compat-table/es2016plus/#test-RegExp_named_capture_groups https://kangax.github.io/compat-table/es2016plus/#test-RegEx...
- SiVal 8y agoThis was a status report on multiple, changing features as of two years ago. The people who know best are probably busy building, but I can't help wondering if anyone is able to provide the current status of any of these things.