1. ホーム
  2. スクリプト・コラム
  3. ルビートピックス

Ruby正規表現とサンプルコード

2022-01-03 08:56:21

puppetのppファイルを書く際、多くのruby正規表現が使われますが、一般的なものは以下の通りです。

正規表現です。

[codesyntax lang="ruby"] となります。

{}: the number of repetitions (e.g. {4} means the preceding element will be repeated exactly 4 times)
{m,n}: The preceding element occurs at least m times and at most n times
[]: range descriptor (e.g. [a-z] means a letter in the range a-z)
\w: character or number, equivalent to [0-9A-Za-z]
\W: non-letter or number
\s: [\t\n\r\f] empty character, equivalent to [\t\n\r\f]
\S: non-empty character
\d: [0-9] numeric, equivalent to [0-9]
\D: non-numeric character
*: 0 or more occurrences of the preceding element
+: 1 or more occurrences of the preceding element
? : The preceding element occurs at most 1 time
|: Matching with the preceding or following expression
\b: backspace (0x08) (only when inside the range descriptor)
\b: word boundary (when outside the range descriptor)
\B: non-word boundary


インスタンスです。[codesyntax lang="ruby"] です。

=begin
Non-negative integers (positive integers + 0): ^\d+$
Positive integers: ^[0-9]*[1-9][0-9]*$
Non-positive integer (negative integer + 0): ^((-\d+)|(0+))$
String consisting of 26 letters: ^[A-Za-z]+$
String consisting of numbers and 26 letters: ^[A-Za-z0-9]+$
E-mail address: ^[\w-]+(\. [\w-]+)*@[\w-]+(\. [\w-]+)+$
Year-Month-Day.
Chinese characters: [\u4e00-\u9fa5]
Double-byte characters (including Chinese characters): [^\x00-\xff]
HTML tags: /<. *>. *<\/\1>|<. *>\/>/
Account number is legal or not (starts with a letter, 5-16 bytes allowed, alphanumeric underscore allowed): ^[A-Za-z][a-zA-Z0-9_]{4,15}$
Phone number: (\d{3}-|\d{4}-)? (\d{8}|\d{7})?
Tencent QQ number: ^[1-9]*[1-9][0-9]*$


お読みいただきありがとうございます。お役に立てれば幸いです。また、このサイトを支持していただきありがとうございます