|
| 1 | +.. role:: emoji-size |
| 2 | + |
| 3 | +.. meta:: |
| 4 | + :description: کتاب آموزش زبان برنامه نویسی پایتون به فارسی، آموزش ماژول re در پایتون، عبارات باقاعده در پایتون، Regular expression در پایتون، regex در پایتون |
| 5 | + :keywords: آموزش, آموزش پایتون, آموزش برنامه نویسی, پایتون, تابع, کتابخانه, پایتون, re |
| 6 | + |
| 7 | + |
| 8 | +درس ۱۶: Regular Expression در پایتون - بخش ۲ |
| 9 | +============================================================================ |
| 10 | + |
| 11 | +این درس در ادامه درس قبل (پانزدهم) میباشد و به شرح تابعهای کاربردی موجود در ماژول ``re`` پایتون میپردازد. پیش از مطالعه این درس میبایست حتما درس قبل را نیز مطالعه کرده باشید. |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +:emoji-size:`✔` سطح: متوسط |
| 18 | + |
| 19 | +---- |
| 20 | + |
| 21 | + |
| 22 | +.. contents:: سرفصلها |
| 23 | + :depth: 2 |
| 24 | + |
| 25 | +---- |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | +توابع جستجو |
| 31 | +--------------------------------------- |
| 32 | + |
| 33 | +توابع پرکاربرد ماژول ``re`` پایتون مرتبط با عمل جستجو در یک متن عبارتند از: |
| 34 | + |
| 35 | +* ``search`` |
| 36 | +* ``match`` |
| 37 | +* ``fullmatch`` |
| 38 | +* ``findall`` |
| 39 | +* ``finditer`` |
| 40 | + |
| 41 | + |
| 42 | +تابع ``search`` |
| 43 | +~~~~~~~~~~~~~~~~~~~~~~ |
| 44 | + |
| 45 | + |
| 46 | +``search(pattern, string, flags=0)`` |
| 47 | + |
| 48 | +تابع ``search`` به دنبال اولین انطباق pattern در string میگردد، در صورت موفقیت یک شی ``Match`` [`اسناد پایتون <https://docs.python.org/3/library/re.html#match-objects>`__] و در غیر این صورت ``None`` برمیگرداند [`اسناد پایتون <https://docs.python.org/3/library/re.html#re.search>`__]:: |
| 49 | + |
| 50 | + |
| 51 | + >>> # Python 2.x |
| 52 | + >>> |
| 53 | + >>> import re |
| 54 | + >>> |
| 55 | + >>> match = re.search('Py...n', 'Python is great') |
| 56 | + >>> |
| 57 | + >>> type(match) |
| 58 | + <type '_sre.SRE_Match'> |
| 59 | + >>> |
| 60 | + |
| 61 | +:: |
| 62 | + |
| 63 | + |
| 64 | + >>> # Python 3.x |
| 65 | + >>> |
| 66 | + >>> import re |
| 67 | + >>> |
| 68 | + >>> match = re.search('Py...n', 'Python is great') |
| 69 | + >>> |
| 70 | + >>> type(match) |
| 71 | + <class 're.Match'> |
| 72 | + |
| 73 | + |
| 74 | +اجازه بدهید یادآوری کنیم که دو نمونه کد زیر عملکردی معادل یکدیگر دارند:: |
| 75 | + |
| 76 | + |
| 77 | + >>> pattern = re.compile('Py...n') |
| 78 | + >>> match = pattern.search('Python is great') |
| 79 | + |
| 80 | +:: |
| 81 | + |
| 82 | + >>> match = re.search('Py...n', 'Python is great') |
| 83 | + |
| 84 | + |
| 85 | + |
| 86 | +شی ``Match`` پایتون |
| 87 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 88 | + |
| 89 | + |
| 90 | +:: |
| 91 | + |
| 92 | + >>> pattern = re.compile('Py...n') |
| 93 | + >>> match = pattern.search('Python is great') |
| 94 | + >>> |
| 95 | + >>> if match: |
| 96 | + ... print(match.group()) |
| 97 | + ... else: |
| 98 | + ... print("pattern not found") |
| 99 | + ... |
| 100 | + Python |
| 101 | + >>> |
| 102 | + |
| 103 | +:: |
| 104 | + |
| 105 | + >>> dir(match) |
| 106 | + ['__class__', '__copy__', '__deepcopy__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'end', 'endpos', 'expand', 'group', 'groupdict', 'groups', 'lastgroup', 'lastindex', 'pos', 're', 'regs', 'span', 'start', 'string'] |
| 107 | + |
| 108 | +در ادامه به بررسی برخی از متدهای مهم این شی میپردازیم: |
| 109 | + |
| 110 | + |
| 111 | + * ``Match.group([group1, ...])`` [`اسناد پایتون <https://docs.python.org/3/library/re.html#re.Match.group>`__] |
| 112 | + |
| 113 | + این متد از شی ``Match``، گروه (های) تطبیق داده شده بر اساس الگو مورد نظر را برمیگرداند. این متد میتواند یک یا چند آرگومان عددی دریافت کند که معرف اندیس گروه مورد نظر میباشد. در حالت فراخوانی بدون آرگومان تمامی گروههای تطبیق داده شده به صورت یک مقدار رشته برگردانده میشود و در صورتی تنها یک مقدار به آن ارسال گردد، گروه تطبیق داده شده متناظر با آن اندیس (شمارش اندیسها از یک است) در قالب یک شی رشته برگردانده میشود و در صورتی که بیش از یک اندیس به عنوان آرگومان ارسال گردد یک شی تاپل محتوی گروههای تطبیق داده شده برگردانده خواهد شد. چنانچه آرگومان ارسالی عددی منفی باشد یا اندیسی بالاتر از تعداد گروههای تطبیق داده شده باشد، یک استثنا ``IndexError`` رخ خواهد داد:: |
| 114 | + |
| 115 | + >>> match = re.search(r"(\w+) (\w+)", "Isaac Newton, physicist") |
| 116 | + >>> match.group() # The entire match |
| 117 | + 'Isaac Newton' |
| 118 | + >>> match.group(0) # The entire match |
| 119 | + 'Isaac Newton' |
| 120 | + >>> match.group(1) # The first parenthesized subgroup. |
| 121 | + 'Isaac' |
| 122 | + >>> match.group(2) # The second parenthesized subgroup. |
| 123 | + 'Newton' |
| 124 | + >>> match.group(1, 2) # Multiple arguments give us a tuple. |
| 125 | + ('Isaac', 'Newton') |
| 126 | + |
| 127 | + >>> match.group(3) |
| 128 | + Traceback (most recent call last): |
| 129 | + File "<stdin>", line 1, in <module> |
| 130 | + IndexError: no such group |
| 131 | + |
| 132 | + در صورتی که الگو مورد نظر شامل هیچ گروهبندی نباشد، فراخوانی بدون آرگومان (یا ارسال آرگومان صفر) این متد، تمام متن تطبیق داده شده را برمیگرداند:: |
| 133 | + |
| 134 | + |
| 135 | + >>> pattern = re.compile('Py...n') |
| 136 | + >>> match = pattern.search('Python is great') |
| 137 | + >>> match.group() |
| 138 | + 'Python' |
| 139 | + |
| 140 | + >>> match.group(0) |
| 141 | + 'Python' |
| 142 | + |
| 143 | + >>> match.group(1) |
| 144 | + Traceback (most recent call last): |
| 145 | + File "<stdin>", line 1, in <module> |
| 146 | + IndexError: no such group |
| 147 | + >>> |
| 148 | + |
| 149 | + |
| 150 | + |
| 151 | + |
| 152 | + * ``Match.groups(default=None)`` [`اسناد پایتون <https://docs.python.org/3/library/re.html#re.Match.groups>`__] |
| 153 | + |
| 154 | + این متد تمام گروههای تطبیق داده شده بر اساس الگو مورد نظر را در قالب یک شی تاپل برمیگرداند. این متد میتواند یک آرگومان بپذیرد که معرف مقدار پیشفرض برای جایگذاری گروههایی است که در رشته ورودی تطبیق داده نشدهاند، در حالت عادی (بدون ارسال آرگومان) این مقدار برابر با ``None`` است:: |
| 155 | + |
| 156 | + >>> match = re.search("(\d+)\.(\d+)", "24.1632") |
| 157 | + >>> match.groups() |
| 158 | + ('24', '1632') |
| 159 | + |
| 160 | + :: |
| 161 | + |
| 162 | + >>> match = re.search("(\d+)\.?(\d+)?", "24") |
| 163 | + >>> match.groups() # Second group defaults to None. |
| 164 | + ('24', None) |
| 165 | + >>> match.groups('0') # Now, the second group defaults to '0'. |
| 166 | + ('24', '0') |
| 167 | + |
| 168 | + |
| 169 | + :: |
| 170 | + |
| 171 | + >>> pattern = re.compile('Py...n') # The pattern is without grouping |
| 172 | + >>> match = pattern.search('Python is great') |
| 173 | + >>> match.groups() |
| 174 | + () |
| 175 | + |
| 176 | + |
| 177 | + * ``Match.groupdict(default=None)`` [`اسناد پایتون <https://docs.python.org/3/library/re.html#re.Match.groupdict>`__] |
| 178 | + |
| 179 | + این متد یک شی دیکشنری (dict) حاوی حاصل تطابق تمام گروههای بانام (Named Groups) موجود در الگو را برمیگرداند:: |
| 180 | + |
| 181 | + |
| 182 | + >>> import re |
| 183 | + |
| 184 | + >>> match = re.search(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Elvis Presley") |
| 185 | + >>> match.groupdict() |
| 186 | + {'first_name': 'Elvis', 'last_name': 'Presley'} |
| 187 | + |
| 188 | + >>> match.group() |
| 189 | + 'Elvis Presley' |
| 190 | + >>> match.group(1) |
| 191 | + 'Elvis' |
| 192 | + >>> match.group(2) |
| 193 | + 'Presley' |
| 194 | + |
| 195 | + >>> match.groups() |
| 196 | + ('Elvis', 'Presley') |
| 197 | + |
| 198 | + این متد نیز همانند متد ``groups`` یک پارامتر اختیاری دارد که در صورت ارسال آرگومان به آن به جای مقدار پیشفرض ``None`` برای حاصل عدم تطابق گروههای موجود در الگو قرار میگیرد:: |
| 199 | + |
| 200 | + >>> import re |
| 201 | + |
| 202 | + >>> match = re.search("(?P<first_name>\w+) (?P<nick_name>`\w+`\s)?(?P<last_name>\w+)", "Elvis `The King` Presley") |
| 203 | + >>> match.groupdict() |
| 204 | + {'first_name': 'Elvis', 'nick_name': '`The King` ', 'last_name': 'Presley'} |
| 205 | + |
| 206 | + >>> match = re.search("(?P<first_name>\w+) (?P<nick_name>`\w+`\s)?(?P<last_name>\w+)", "Elvis Presley") |
| 207 | + >>> match.groupdict() |
| 208 | + {'first_name': 'Elvis', 'nick_name': None, 'last_name': 'Presley'} |
| 209 | + |
| 210 | + >>> match.groupdict("---") # or match.groupdict(default="---") |
| 211 | + {'first_name': 'Elvis', 'nick_name': '---', 'last_name': 'Presley'} |
| 212 | + |
| 213 | + |
| 214 | + |
| 215 | + * ``Match.start([group])`` [`اسناد پایتون <https://docs.python.org/3/library/re.html#re.Match.start>`__] ``Match.end([group])`` [`اسناد پایتون <https://docs.python.org/3/library/re.html#re.Match.end>`__] |
| 216 | + |
| 217 | + متن رشته خروجی (تطبیق یافته بر اساس الگو مورد نظر) را در نظر بگیرید، متد ``start`` اندیس شروع این متن از رشته ورودی و متد ``end`` اندیس نقطه پایان را برمیگرداند. این دو متد میتوانند یک آرگومان اختیاری نیز دریافت کنند که معرف اندیس یک گروه مشخص در الگو میباشد، با ارسال این آرگومان نتایج بر اساس تکه متن تطبیق داده شده با آن گروه برگردانده خواهد شد:: |
| 218 | + |
| 219 | + >>> email = "tony@tiremove_thisger.net" |
| 220 | + >>> match = re.search("remove_this", email) |
| 221 | + >>> match.start() |
| 222 | + 7 |
| 223 | + >>> match.end() |
| 224 | + 18 |
| 225 | + >>> email[match.start() : match.end()] |
| 226 | + 'remove_this' |
| 227 | + >>> email[:match.start()] + email[match.end():] |
| 228 | + 'tony@tiger.net' |
| 229 | + |
| 230 | + :: |
| 231 | + |
| 232 | + >>> match = re.search(r"(\d+)\.(\d+)", "24.1632") |
| 233 | + |
| 234 | + >>> match.start() |
| 235 | + 0 |
| 236 | + >>> match.end() |
| 237 | + 7 |
| 238 | + |
| 239 | + >>> match.start(1) |
| 240 | + 0 |
| 241 | + >>> match.end(1) |
| 242 | + 2 |
| 243 | + |
| 244 | + >>> match.start(2) |
| 245 | + 3 |
| 246 | + >>> match.end(2) |
| 247 | + 7 |
| 248 | + >>> |
| 249 | + |
| 250 | + |
| 251 | + * ``Match.span([group])`` [`اسناد پایتون <https://docs.python.org/3/library/re.html#re.Match.span>`__] |
| 252 | + |
| 253 | + این متد یک شی تاپل دوتایی از خروجی دو متد ``start`` و ``end`` را بر میگرداند و همانند آنها نیز یک آرگومان اختیاری دارد - نمونه خروجی: ``(m.start(group), m.end(group))``:: |
| 254 | + |
| 255 | + >>> match = re.search(r"(\d+)\.(\d+)", "24.1632") |
| 256 | + >>> match.span() |
| 257 | + (0, 7) |
| 258 | + >>> match.span(1) |
| 259 | + (0, 2) |
| 260 | + >>> match.span(2) |
| 261 | + (3, 7) |
| 262 | + >>> match.span(3) |
| 263 | + Traceback (most recent call last): |
| 264 | + File "<stdin>", line 1, in <module> |
| 265 | + IndexError: no such group |
| 266 | + |
| 267 | + * ``Match.re`` [`اسناد پایتون <https://docs.python.org/3/library/re.html#re.Match.re>`__] ``Match.string`` [`اسناد پایتون <https://docs.python.org/3/library/re.html#re.Match.string>`__] |
| 268 | + |
| 269 | + این دو متغیر به ترتیب حاوی شی RegEx الگو و متن مورد نظر جهت انجام عملیات تطابق خواهند بود:: |
| 270 | + |
| 271 | + >>> email = "tony@tiremove_thisger.net" |
| 272 | + >>> match = re.search("remove_this", email) |
| 273 | + |
| 274 | + >>> match.re |
| 275 | + re.compile('remove_this') |
| 276 | + |
| 277 | + >>> match.string |
| 278 | + 'tony@tiremove_thisger.net' |
| 279 | + |
| 280 | + >>> match.string[match.start() : match.end()] |
| 281 | + 'remove_this' |
| 282 | + |
| 283 | + :: |
| 284 | + |
| 285 | + >>> match = re.search(r"(\d+)\.(\d+)", "24.1632") |
| 286 | + |
| 287 | + >>> match.re |
| 288 | + re.compile('(\\d+)\\.(\\d+)') |
| 289 | + |
| 290 | + >>> match.string |
| 291 | + '24.1632' |
| 292 | + |
| 293 | + |
| 294 | + |
| 295 | + |
| 296 | + |
| 297 | + |
| 298 | +| |
| 299 | +
|
| 300 | +---- |
| 301 | + |
| 302 | +:emoji-size:`😊` امیدوارم مفید بوده باشه |
| 303 | + |
| 304 | +`لطفا دیدگاه و سوالهای مرتبط با این درس خود را در کدرز مطرح نمایید. <http://www.coderz.ir/python-tutorial-re-regex/>`_ |
| 305 | + |
| 306 | + |
| 307 | + |
0 commit comments