Skip to content

Instantly share code, notes, and snippets.

@atmin
Created October 18, 2013 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atmin/7039038 to your computer and use it in GitHub Desktop.
Save atmin/7039038 to your computer and use it in GitHub Desktop.
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