We've organized the main regular expression patterns for beginners.
pattern | meaning |
---|---|
[a-z] | Matches any one of the characters enclosed in square brackets (in this case matches any of the characters a through z) |
\d | Match numbers |
\D | Match other than numbers |
{n} | Matches the previous pattern that repeats n times |
{n, m} | Matches the previous character that appears at least n times and at most m times |
. | Matches any single character except newline |
* | Matches 0 or more repetitions of the previous subexpression |
+ | Matches one or more repetitions of the previous subexpression |
\A | The character string immediately after matches the character string at the beginning |
\z | The previous string matches the trailing string |
?= | Matches the character string immediately after the set character |
*? | Check the character string in which the character set immediately before continues 0 times or more,?Returns one character when the character immediately after |
pattern | meaning |
---|---|
/i | Case insensitive |
pattern | meaning |
---|---|
* | Matches 0 or more repetitions of the previous character |
Since it is a little difficult to understand "match 0 or more repetitions" of "*", check it by comparing with "+".
pattern | meaning | Examples of matching strings |
---|---|---|
a.*z | A string of two or more digits starting with a and ending with z | az, abz,abcz etc. |
a.+z | A string of 3 or more digits starting with a and ending with z | abz,abcz etc. |
Since "\ *" itself does not require a character string of one or more digits, a two-digit character string will match as in the above example. "." Matches any character except a newline, but with a "\ *" after it, it matches even if there is no character corresponding to ".". On the other hand, "+" asks for a character string with one or more digits, so it does not match a two-digit character string.
pattern | meaning |
---|---|
/\A[Ah-Hmm-One-龥]/ | Full-width hiragana, full-width katakana, kanji |
/\A[A-Car-]+\z/ | Full-width katakana |
/\A[a-zA-Z0-9]+\z/ | Half-width alphanumeric |
/\A\d{3}[-]\d{4}\z/ | Postal code("-And 7 digits) |
Unlike regular expressions, Rails' ActiveRecord validation helper, numericity, allows you to easily configure validation with the following options:
pattern | meaning |
---|---|
greater_than_or_equal_to: 〇〇 | Numbers over 〇〇 |
less_than_or_equal_to: 〇〇 | Numbers below 〇〇 |
There is a site called Rubular where you can try regular expressions that can be used in Ruby. It is a useful site to deepen your understanding of regular expressions because you can check whether the regular expressions you created match the intended character strings and patterns.
Ruby 3.0.0 Reference Manual> Regular Expressions Rails Guide v6.0 Active Record Validation (https://railsguides.jp/active_record_validations.html) murashun.jp Basic regular expression list TechRacho [Series: Regular Expression] Unicode Character Properties (1)
Recommended Posts