What is the regex pattern for a regex pattern? I am using Ruby version 1.8.7, and have a requirement to determine if a given string is a regex pattern. What is the best pattern to use to determine this?
Thanks, Anand
What is the regex pattern for a regex pattern? I am using Ruby version 1.8.7, and have a requirement to determine if a given string is a regex pattern. What is the best pattern to use to determine this?
Thanks, Anand
well any word can be a regex pattern. The string "cat" could be compiled to a regex pattern. You could do something like:
def is_regex?(str)
Regexp.new(str) rescue false
end
/(/ is not a valid regex for any regex engine where parentheses are special by default (which is most of them).There isn't one, since regexes themselves aren't a regular language (due to things like matching parentheses).
If you want to determine whether something is a valid regex, I'd recommend just trying to compile it as a regex and see if it fails.
Assuming the regex pattern is a string with two forward slashes, / defining the pattern, then the regex to find a pattern with two foward slashes at the beginning and end of a pattern is as following:
(\/(?:.)*\/(?:i|g|s|m|U)*)
(?:i|g|s|m|U) should be [igsmU]. Except those modifiers aren't valid; in Ruby 1.8.7 (without the Oniguruma Gem), only [imox] are allowed.