A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.
Here's an example: var stringToGoIntoTheRegex = "abc"; var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g"); // at this point, the line above is the same as: var regex = /#abc#/g; var input = "Hello this is #abc# some #abc# stuff."; var output = input. replace(regex, "!!"); alert(output); // Hello this is !!
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.
Ruby | Regexp match() function Regexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search.
You can use #{}
just like in a string.
1.9.2p290 :001 > some_string = "033112"
=> "033112"
1.9.2p290 :002 > a_regex = /[A-Z]{1,4}#{some_string}[A-Z]{1-5}-EQB.html/
=> /[A-Z]{1,4}033112[A-Z]{1-5}-EQB.html/
I fully support Isaac's solution, but you can also:
a = "\/static\/workout\/[A-Z]{1,4}" + "033112" + "[A-Z]{1,5}-EQB.html"
regex = Regexp.new(a)
stringtomatch =~ regex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With