Skip to content

Instantly share code, notes, and snippets.

@svineet
Created August 17, 2013 07:01
Show Gist options
  • Save svineet/6255659 to your computer and use it in GitHub Desktop.
Save svineet/6255659 to your computer and use it in GitHub Desktop.
Method -chaining implementation of [VerEx](http://verbalexpressions.github.io/) in Ruby. The other [implementation](https://github.com/ryan-endacott/verbal_expressions) uses DSL. This is just a emperiment. May have a lot of bugs, and is not by any means complete.
# This is a program trying to implement Verbal Expressions
# See this for more info - http://verbalexpressions.github.io/
def VerEx
return VerExClass.new
end
class VerExClass
@regex = "" # The main regex variable
def intitialize reg
@regex = reg
end
def final_regex
return @regex
end
def add value
@regex << value
end
def start_of_line
if @regex == nil
@regex = "^"
else
self.add("^")
end
return self
end
def end_of_line
self.add("$")
return self
end
def find value
self.add("(" + Regexp.escape(value) + ")")
return self
end
def then value
return self.find Regexp.escape(value)
end
def maybe value
self.add("(" + Regexp.escape(value) + ")?")
return self
end
def anything
self.add("(?:.*)")
return self
end
def anything_but value
self.add("([^" + Regexp.escape(value) + "]*)")
return self
end
def something
self.add("(?:.+)")
return self
end
def something_but value
self.add("(?:[^" + Regexp.escape(value) + "]+)")
return self
end
def line_break
self.add("(?:(?:\n)|(?:\r\n))")
return self
end
def tab
self.add("\t")
end
def match matching_string
return Regexp.compile(@regex).match(matching_string)
end
end
# Tests -
if __FILE__ == $0
reg2 = VerEx().
start_of_line.
find('http').
maybe('s').
find('://').
maybe('www.').
anything_but(' ').
end_of_line()
if (reg2.match "https://www.google.com")
puts "Matched"
else
puts "Not matched"
end
puts reg2.final_regex
puts "^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$"
if %r ^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$ .match "https://google.com"
puts "True"
end
end
@svineet
Copy link
Author

svineet commented Aug 19, 2013

Interesting....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment