עוגנים
שיעור 12 מתוך 28 בקורס ביטויים רגולריים ב-Python של Coddy.
עוגנים הם תווים מיוחדים בביטויים רגולריים שמתאימים למיקומים ולא לתווים ממשיים. שני העוגנים הנפוצים ביותר הם ^ ו-$.
<strong>^</strong>: מתאים לתחילת מחרוזת.<strong>$</strong>: מתאים לסוף מחרוזת.
import re
text = "Hello, world!"
pattern_start = r"^Hello"
pattern_end = r"world!$"
match_start = re.search(pattern_start, text)
match_end = re.search(pattern_end, text)
if match_start:
print("Start anchor match found:", match_start.group()) # פלט: Start anchor match found: Hello
else:
print("No start anchor match found")
if match_end:
print("End anchor match found:", match_end.group()) # פלט: End anchor match found: world!
else:
print("No end anchor match found")בדוגמה שלמעלה, התבנית ^Hello מתאימה ל-"Hello" בתחילת המחרוזת, והתבנית world!$ מתאימה ל-"world!" בסוף המחרוזת
אתגר
קלכתבו פונקציה בשם find_lines_starting_with שמקבלת רשימה של מחרוזות ומילה כקלט, ומחזירה רשימה של מחרוזות שמתחילות במילה הנתונה.
נסו בעצמכם
import re
def find_lines_starting_with(lines, word):
# כתבו כאן קודכל השיעורים ביחידה ביטויים רגולריים ב-Python
1מבוא
מבואתרגלו בעצמכם: קומפיילר Python אונליין