| Start |
|---|
=~ operator Note: The order is significant. Though
Note that this does not return a true/false value, it instead returns either the index of the match if found, or nil if not found. Because all integers in ruby are truthy (including 0) and nil is falsy, this works. If you want a boolean value, use |
| Regular Expressions in Case Statements You can test if a string matches several regular expressions using a switch statement. ExampleThis works because case statements are checked for equality using the |
| Groups, named and otherwise. Ruby extends the standard group syntax The index of the match is counted based on the order of the left parentheses (with the entire regex being the first group at index 0) |
| Quantifiers Quantifiers allows to specify count of repeated strings. By default, quantifiers are greedy (opens new window), which means they take as many characters as they can while still making a match. Normally this is not noticeable: The named capture group This version will still match, but the named capture will include 'Stack Exchange' since Appending |
| Character classes Describes ranges of symbols You can enumerate symbols explicitly Or use ranges It is possible to combine ranges and single symbols Leading dash ( Classes can be negative when preceding symbols with There are some shortcuts for widespread classes and special charachters, plus line endings
To escape any reserved charachter, such as |
| Defining a Regexp A Regexp can be created in three different ways in Ruby. |
| match? - Boolean Result Returns Ruby 2.4+ |
| Common quick usage Regular expressions are often used in methods as parameters to check if other strings are present or to search and/or replace strings. You'll often see the following: So you can simply use this as a check if a string contains a substring More advanced but still short and quick: search for a specific group by using the second parameter, 2 is the second in this example because numbering starts at 1 and not 0, a group is what is enclosed in parentheses. Also often used: search and replace with The last result is remembered and can be used on the following lines |
Read Article
https://develop.horje.com/learn/1434/reference