ورقة غش لأساسيات التعبيرات النمطية

التعبير النمطي (regex) هو نمط يطابق النص. كل رمز، يسمى token، يغير سلوك النمط. تجمع الورقة أدناه أهم الرموز مع معنى مبسط ومثال صغير يمكن نسخه وتجربته.

آخر تحديث:

الرمزالمعنىمثال
.Matches any single character except newline.a.c matches abc, a c
*Matches the preceding token zero or more times.ab* matches a, abb
+Matches the preceding token one or more times.ab+ matches ab, abb
?Makes the preceding token optional (zero or one).colou?r matches color, colour
[]Character set: matches any one character inside.[aeiou] matches any vowel
[^]Negated set: matches any character NOT inside.[^0-9] matches any non-digit
\dMatches any digit (0-9).\d+ matches 42, 007
\wMatches any word character (a-z, A-Z, 0-9, _).\w+ matches hello_1
\sMatches any whitespace (space, tab, newline).a\sb matches a b
^Anchors the match to the start of a line/string.^Hello matches start of string
$Anchors the match to the end of a line/string.world$ matches end of string
|Alternation: matches the pattern on either side.cat|dog matches cat or dog
()Groups a sub-pattern (and captures it).(ab)+ matches ab, abab
{n,m}Quantifier: match the preceding token n to m times.a{2,4} matches aa, aaaa
(?i)Inline flag: makes the pattern case-insensitive.(?i)hello matches HELLO

ملاحظات

الأسئلة الشائعة

بماذا يطابق الرمز (.)؟
افتراضيًا يطابق النقطة أي حرف ما عدا سطرًا جديدًا. لمطابقة نقطة حرفية يجب تهريبها كـ \.
ما الفرق بين * و +؟
النجمة * تطابق الرمز السابق صفرًا أو أكثر من مرة، لذا 'ab*' تطابق أيضًا 'a'. علامة الجمع + تتطلب واحدًا على الأقل، فتطابق 'ab' لكن ليس 'a' وحدها.
كيف أطابق رقمًا أو حرف كلمة؟
استخدم \d لأي رقم (0-9) و\w لأي حرف كلمة (أحرف وأرقام وشرطة سفلية). نفيها هو \D و\W.
ماذا يفعلان ^ و $؟
^ يثبّت المطابقة عند بداية السلسلة أو السطر؛ و$ عند النهاية. معًا، ^نمط$ يجبر السلسلة بأكملها على المطابقة.