Created
October 18, 2013 09:32
-
-
Save atmin/7039038 to your computer and use it in GitHub Desktop.
JavaScript RegExp monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Need this in JavaScript? Use coffeescript.org "Try CoffeeScript" | |
# A micro DSL for building maintainable, complex, dynamic regular expressions | |
reBuild = -> | |
re = '' | |
self = { | |
# Append regular expression | |
re: (s) -> | |
re += s | |
self | |
# Append literal text, escape regexp chars | |
text: (s) -> | |
re += (s + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1') | |
self | |
# open capturing group | |
capture: -> | |
re += '(' | |
self | |
# open non-capturing group | |
group: -> | |
re += '(?:' | |
self | |
# end group | |
end: -> | |
re += ')' | |
self | |
# add other helpers, if needed | |
# result | |
asString: -> re | |
asRegExp: -> new RegExp(re) | |
} | |
# Define your primitive regular expressions | |
RE_IDENTIFIER = '\\w+' | |
RE_ANYTHING = '[\\s\\S]*?' | |
# Build your regexp, like | |
reBuild() | |
.re(RE_ANYTHING) | |
.group().re(IDENTIFIER).end() | |
.text(' followed by this literal text') | |
.asRegExp() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment