What's the difference between string.match(regex) and regex.match(string) in Ruby? What's the justification for having both those constructs in the language?
Short for regular expression, a regex is a string of text that lets you create patterns that help match, locate, and manage text. Perl is a great example of a programming language that utilizes regular expressions. However, its only one of the many places you can find regular expressions.
There are also two types of regular expressions: the "Basic" regular expression, and the "extended" regular expression. A few utilities like awk and egrep use the extended expression. Most use the "basic" regular expression.
Use . test if you want a faster boolean check. Use . match to retrieve all matches when using the g global flag.
A Regular Expression (abbr. RegEx) is a pattern of characters used to match different combinations of strings or characters.
A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
Regular expressions are just strings themselves. Each character in a regular expression can either be part of a code that makes up a pattern to search for, or it can represent a letter, character or word itself.
Aside from hanging off of different objects (which sometimes makes it more convenient to call one instead of the other), they are the same. The justification is that they are both useful and one is sometimes more convenient than the other.
I thnk that, intuitively, match
, or the related method =~
, expresses some kind of equality, as reflected in the fact that =~
includes the equality =
and the equivalence ~
relations (not in ruby but in mathematics). But it is not totally an equivalence relation, and among the three axioms of equality (reflexivity, commutativity, transitivity), particularly commutativity seems reasonable to be maintaind in this relation; it is natural for a programmer to expect that string.match(regex)
or string =~ regex
would mean the same thing as regex.match(string)
or regex =~ string
. I myself, would have problem remembering if either is defined and not the other. In fact, some people feel it strange that the method ===
, which also reminds us of some kind of equality, is not commutative, and have raised questions.
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