Skip to content

Instantly share code, notes, and snippets.

@atmin
Created Oct 18, 2013
Embed
What would you like to do?
JavaScript RegExp monad
# 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