RegExp and/or methods

Two new "and" and "or" methods on RegExp objects that concats regex's into and/or sequences

/\w/.and(/\d/, /\s/).or(/\S/)

Becomes the final RegExp

/(?=(?=\w)(?=\d)(?=\s))|(\S)/

A better example of this would be if the inline RegExp expressions where distinct variables there where used also used else where, that you could import and compose into another RegExp.

This is interesting. I'm curious what the polyfill would look like.

Some related content:

1 Like

@thysultan the .or method is straightforward, the meaning of .and however less so, especially if you want to further compose the RegExps.

RegExps (and formal grammars, more generally) already have an and operator: the pattern sequence, which is represented as concatenation/juxtaposition in most notations. The identity for the operator is a pattern that always matches. /(?:)a/ === /a(?:)/ === /a/.

As for or operations, the disjunction's identity is a pattern that always fails: /a|$./===/$.|a/===/a/`.

There's another and operation in the works, as the character set intersection operation per the v flag proposal (which I think, beside set operations, gets everything backwards, but that's another matter): GitHub - tc39/proposal-regexp-v-flag: UTS18 set notation in regular expressions.

You're proposing a third kind of semantics here... I kind of see why you'd want to punt on how much characters the result consumes, by consuming none... It's an interesting solution.

If you want to polyfill your idea, you can use

import {sequence, either, lookAhead} from 'compose-regexp'

RegExp.prototype.and = function(...args) {
  return sequence(lookAhead(this), ...args.map(x => lookAhead(x)))
}

RegExp.prototype.or = function(...args) {
  return either(this, ...args)
}

Here's a demo with your example

(edit: the top-level look ahead is not necessary for .and, /(?=(?=A)(?=B))/ and /(?=A)(?=B)/ match the same things).