דף כיסום ליסודות הביטויים הרגולריים

ביטוי רגולרי (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

הערות

שאלות נפוצות

עם מה מתאים הנקודה (.) ?
כברירת מחדל הנקודה מתאימה לכל תו פרט לתו שורה חדשה. כדי להתאים נקודה עצמה יש לבצע לה escape באמצעות \.
מה ההבדל בין * ל-+ ?
הכוכבית * מתאימה את הסמל הקודם אפס פעמים או יותר, לכן 'ab*' מתאימה גם ל-'a'. הסימן + דורש לפחות אחת, מתאים ל-'ab' אך לא ל-'a' לבדה.
איך מתאימים ספרה או תו מילה?
השתמש ב-\d לכל ספרה (0-9) וב-\w לכל תו מילה (אותיות, ספרות וקו תחתון). השלילות הן \D ו-\W.
למה משמשים ^ ו-$ ?
הסימן ^ מעגן את ההתאמה לתחילת המחרוזת או השורה; $ לסופה. יחד, ^תבנית$ מאלץ את כל המחרוזת להתאים.