Ruby regular expression explanation and sample code

Time:2021-11-15

Many Ruby regular expressions are used in writing the PP file of puppet. The common regular expressions are as follows:

Regular expression:

[codesyntax lang=”ruby“]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{}: number of repetitions (e.g{4}Indicates that the previous will repeat4(Times)
{m, n}: the previous element appears at least m times and at most N times
[]: range descriptor (e.g. [A-Z] represents a letter in the A-Z range)
\w: Characters or numbers, equivalent to[0-9A-Za-z]
\W: not alphanumeric
\s: [\ t \ n \ R \ F] null character, equivalent to [\ t \ n \ R \ F]
\S: non empty character
\d: [0-9]Number, equivalent to[0-9]
\D: non numeric characters
*: previous element appears0One or more times
+: previous element appears1One or more times
?: Previous elements appear at most1second
|: matches the preceding or following expression
\b: Backspace (0x08) (only inside the range descriptor)
\b: Word boundary (when outside the range descriptor)
\B: non word boundary

Example: [codesyntax lang = “Ruby”]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
=begin
Nonnegative integer (positive integer)+0): ^\d+$
Positive integer:^[0-9]*[1-9][0-9]*$
Non positive integer (negative integer)+0): ^((-\d+)|(0+))$
from26A string of English letters:^[A-Za-z]+$
By numbers and26A string of English letters:^[A-Za-z0-9]+$
E-Mail address: ^ [\ W -] + (\. [\ W -] +) * @ [\ W -] + (\. [\ W -] +)+$
MM DD YY:
Chinese characters: [\ u4e00 - \ u9fa5]
Double byte characters (including Chinese characters): [^ \ X00 - \ XFF]
HTMLTag: / <. * >*<\/\1>|<.*>\/>/
Whether the account number is legal (beginning with a letter, allowed)5-16Bytes, alphanumeric underscore allowed):^[A-Za-z][a-zA-Z0-9_]{4,15}$
Phone number: (\ d){3}-|\d{4}-)?(\d{8}|\d{7})?
tencentQQNo.:^[1-9]*[1-9][0-9]*$

Thank you for reading, hope to help you, thank you for your support to this site!