Python regex search

Компилирование

Модуль re позволяет вам «компилировать» выражение, которое вы ищите чаще всего. Это также позволит вам превратить выражение в объект SRE_Pattern. Вы можете использовать этот объект в вашей функции поиска в будущем. Давайте используем код из предыдущего примера и изменим его, чтобы использовать компилирование:

Python

import re

text = «The ants go marching one by one»

strings =

for string in strings:
regex = re.compile(string)
match = re.search(regex, text)
if match:
print(‘Found «{}» in «{}»‘.format(string, text))
text_pos = match.span()
print(text)
else:
print(‘Did not find «{}»‘.format(string))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

importre

text=»The ants go marching one by one»

strings=’the’,’one’

forstringinstrings

regex=re.compile(string)

match=re.search(regex,text)

ifmatch

print(‘Found «{}» in «{}»‘.format(string,text))

text_pos=match.span()

print(textmatch.start()match.end())

else

print(‘Did not find «{}»‘.format(string))

Обратите внимание на то, что здесь мы создаем объект паттерна, вызывая compile в каждой строке нашего списка, и назначаем результат переменной – регулярному выражению. Далее мы передаем это выражение нашей поисковой функции

Остальная часть кода остается неизменной. Основная причина, по которой используют компилирование это сохранить выражение для повторного использования в вашем коде в будущем. В любом случае, компилирование также принимает флаги, которые могут быть использованы для активации различных специальных функций. Мы рассмотрим это далее.Обратите внимание: когда вы компилируете паттерны, они автоматически кэшируются, так что если вы не особо используете регулярные выражения в своем коде, тогда вам не обязательно сохранять компилированный объект как переменную.

Major new features of the 3.9 series, compared to 3.8

Some of the new major new features and changes in Python 3.9 are:

  • PEP 573, Module State Access from C Extension Methods
  • PEP 584, Union Operators in
  • PEP 585, Type Hinting Generics In Standard Collections
  • PEP 593, Flexible function and variable annotations
  • PEP 602, Python adopts a stable annual release cadence
  • PEP 614, Relaxing Grammar Restrictions On Decorators
  • PEP 615, Support for the IANA Time Zone Database in the Standard Library
  • PEP 616, String methods to remove prefixes and suffixes
  • PEP 617, New PEG parser for CPython
  • BPO 38379, garbage collection does not block on resurrected objects;
  • BPO 38692, os.pidfd_open added that allows process management without races and signals;
  • BPO 39926, Unicode support updated to version 13.0.0;
  • BPO 1635741, when Python is initialized multiple times in the same process, it does not leak memory anymore;
  • A number of Python builtins (range, tuple, set, frozenset, list, dict) are now sped up using PEP 590 vectorcall;
  • A number of Python modules (_abc, audioop, _bz2, _codecs, _contextvars, _crypt, _functools, _json, _locale, operator, resource, time, _weakref) now use multiphase initialization as defined by PEP 489;
  • A number of standard library modules (audioop, ast, grp, _hashlib, pwd, _posixsubprocess, random, select, struct, termios, zlib) are now using the stable ABI defined by PEP 384.

You can find a more comprehensive list in this release’s «What’s New» document.

Срез строки

Можете представить способ перевернуть строку, который был бы короче названия функции? А я могу!

Срез строки — вещь прекрасная, но порой пугающая новичков «уплотненным» синтаксисом. Срез содержит три параметра — , аналогично функции . Подробнее о них вы можете прочитать в других статьях на Хабре.

Для способа с использованием срезов не нужно даже создавать функцию, только зря строки и время потратите. Все элементарно — присвоим параметру step значение -1 и пропустим два других параметра, происходит магия — строка переворачивается:

Ввод:

Вывод:

Конечно, никакой магии здесь нет, мы просто перебираем символы с шагом -1, то есть в обратном порядке.

And now for something completely different

trong>Arthur (Eric Idle): Good morning, I’d like to buy a book please.
Bookseller (John Cleese): Oh, well I’m afraid we don’t have any. (trying to hide them)
Arthur: I’m sorry?
Bookseller: We don’t have any books. We’re fresh out of them. Good morning.
Arthur: What are all these?
Bookseller: All what? Oh! All these, ah ah ha ha. You’re referring to these… books.
Arthur: Yes.
Bookseller: They’re um… they’re all sold. Good morning.
Arthur: What all of them?
Bookseller: Every single man-Jack of them. Not a single one of them in an unsold state. Good morning.
Arthur: Wait a minute, there’s something going on here.
Bookseller: What, where? You didn’t see anything did you?
Arthur: No, but I think there’s something going on here.
Bookseller: No no, well there’s nothing going on here at all (shouts off) and he didn’t see anything. Good morning.
Arthur: Oh, well, I’d like to buy a copy of an ‘Illustrated History of False Teeth’.
Bookseller: My God you’ve got guts.
Arthur: What?
Bookseller: (pulling gun) Just how much do you know?
Arthur: What about?
Bookseller: Are you from the British Dental Association?
Arthur: No I’m a tobacconist.
Bookseller: Stay where you are. You’ll never leave this bookshop alive.
Arthur: Why not?
Bookseller: You know too much, my dental friend.
Arthur: I don’t know anything.
Bookseller: Come clean. You’re a dentist aren’t you.
Arthur: No, I’m a tobacconist.
Bookseller: A tobacconist who just happens to be buying a book on teeth?

Version Operating System Description MD5 Sum File Size GPG
Gzipped source tarball Source release 429ae95d24227f8fa1560684fad6fca7 25372998 SIG
XZ compressed source tarball Source release 61981498e75ac8f00adcb908281fadb6 18897104 SIG
macOS 64-bit Intel installer Mac OS X for macOS 10.9 and later 74f5cc5b5783ce8fb2ca55f11f3f0699 29795899 SIG
macOS 64-bit universal2 installer Mac OS X for macOS 10.9 and later, including macOS 11 Big Sur on Apple Silicon (experimental) 8b19748473609241e60aa3618bbaf3ed 37451735 SIG
Windows embeddable package (32-bit) Windows 96c6fa81fe8b650e68c3dd41258ae317 7571141 SIG
Windows embeddable package (64-bit) Windows e70e5c22432d8f57a497cde5ec2e5ce2 8402333 SIG
Windows help file Windows c49d9b6ef88c0831ed0e2d39bc42b316 8787443 SIG
Windows installer (32-bit) Windows dde210ea04a31c27488605a9e7cd297a 27126136 SIG
Windows installer (64-bit) Windows Recommended b3fce2ed8bc315ad2bc49eae48a94487 28204528 SIG

Пример: целевой поисковый продукт Jingdong

Цель: получить информацию на странице поиска JD, извлечь название продукта и цену

Путь: Получить интерфейс поиска Jingdong, отправить запрос поиска и получить результат

Обработка перелистывания страниц

Выполните поиск по «School Bag», чтобы узнать его интерфейс: https://search.jd.com/Search?keyword=%E4%B9%A6%E5%8C%85&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E4%B9%A6%E5%8C%85&stock=1&page=5&s=104&click=0

Часть% E4% B9% A6% E5% 8C% 85 является «школьной сумкой», поэтому https://search.jd.com/Search?keyword является ее интерфейсом поиска.

Ссылка на вторую страницу:

https://search.jd.com/Search?keyword=%E4%B9%A6%E5%8C%85&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E4%B9%A6%E5%8C%85&stock=1**&page=3**&s=52&click=0

Ссылка на третью страницу:

https://search.jd.com/Search?keyword=%E4%B9%A6%E5%8C%85&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E4%B9%A6%E5%8C%85&stock=1**&page=5**&s=104&click=0

Другая часть страницы — это управляющая клавиша для перелистывания страниц, которая фактически является номером начального продукта на второй странице.

Посмотреть соглашение о роботах JD

Шаги программы:

1. Отправьте запрос на поиск товара и получите страницы в цикле

2. Извлеките название продукта и информацию о цене для каждой полученной страницы.

3. Вывести информацию на экран

Программа: Jingdong не может сканировать -_- |||

Поведение и применение символов регулярных выражений.

Синтаксис регулярных выражений в Python немного отличается от синтаксиса регулярных выражений в языке программирования PERL.

Регулярные выражения могут быть объединены для формирования новых регулярных выражений. Если и являются регулярными выражениями, то также является регулярным выражением. В общем, если строка соответствует , а другая строка соответствует , строка будет соответствовать . Это верно, если только или не содержат операций с низким приоритетом — граничные условия между и или пронумерованные ссылки на группы. Таким образом, сложные выражения могут быть легко построены из более простых примитивных выражений.

Для получения дополнительной информации смотрите раздел сайта docs-python.ru «Использование регулярных выражений в Python»

Регулярные выражения могут содержать как специальные, так и обычные символы. Большинство обычных символов, таких как , или , являются простейшими регулярными выражениями, они просто соответствуют друг другу. Вы можете объединять обычные символы, поэтому выражение соответствует строке .

Некоторые символы, такие как или , являются специальными. Специальные символы либо обозначают классы обычных символов, либо влияют на интерпретацию регулярных выражений вокруг них.

Классификаторы, которые осуществляют повтор символов или группы символов , , , не могут быть непосредственно вложены. Это позволяет избежать неоднозначности с суффиксом не жадного модификатора и с другими модификаторами в других реализациях. Чтобы применить второе повторение к внутреннему повторению, можно использовать круглые скобки. Например, выражение соответствует любому кратному шести символов ‘a’.

  • ,

    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • , , — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
  • ,

    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
  • .

    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;
    • — ;

Python Tutorial

Python HOMEPython IntroPython Get StartedPython SyntaxPython CommentsPython Variables
Python Variables
Variable Names
Assign Multiple Values
Output Variables
Global Variables
Variable Exercises

Python Data TypesPython NumbersPython CastingPython Strings
Python Strings
Slicing Strings
Modify Strings
Concatenate Strings
Format Strings
Escape Characters
String Methods
String Exercises

Python BooleansPython OperatorsPython Lists
Python Lists
Access List Items
Change List Items
Add List Items
Remove List Items
Loop Lists
List Comprehension
Sort Lists
Copy Lists
Join Lists
List Methods
List Exercises

Python Tuples
Python Tuples
Access Tuples
Update Tuples
Unpack Tuples
Loop Tuples
Join Tuples
Tuple Methods
Tuple Exercises

Python Sets
Python Sets

Access Set Items
Add Set Items
Remove Set Items
Loop Sets
Join Sets
Set Methods
Set Exercises

Python Dictionaries
Python Dictionaries
Access Items
Change Items
Add Items

Remove Items
Loop Dictionaries
Copy Dictionaries
Nested Dictionaries
Dictionary Methods
Dictionary Exercise

Python If…ElsePython While LoopsPython For LoopsPython FunctionsPython LambdaPython ArraysPython Classes/ObjectsPython InheritancePython IteratorsPython ScopePython ModulesPython DatesPython MathPython JSONPython RegExPython PIPPython Try…ExceptPython User InputPython String Formatting

Согласуемые символы

Когда вам нужно найти символ в строке, в большей части случаев вы можете просто использовать этот символ или строку. Так что, когда нам нужно проверить наличие слова «dog», то мы будем использовать буквы в dog. Конечно, существуют определенные символы, которые заняты регулярными выражениями. Они так же известны как метасимволы. Внизу изложен полный список метасимволов, которые поддерживают регулярные выражения Python:

Python

. ˆ $ * + ? { } | ( )

1 . ˆ $ * + ? { } | ( )

Давайте взглянем как они работают. Основная связка метасимволов, с которой вы будете сталкиваться, это квадратные скобки: . Они используются для создания «класса символов», который является набором символов, которые вы можете сопоставить. Вы можете отсортировать символы индивидуально, например, так: . Это сопоставит любой внесенный в скобки символ. Вы также можете использовать тире для выражения ряда символов, соответственно: . В этом примере мы сопоставим одну из букв в ряде между a и g. Фактически для выполнения поиска нам нужно добавить начальный искомый символ и конечный. Чтобы упростить это, мы можем использовать звездочку. Вместо сопоставления *, данный символ указывает регулярному выражению, что предыдущий символ может быть сопоставлен 0 или более раз. Давайте посмотрим на пример, чтобы лучше понять о чем речь:

Python

‘a*f

1 ‘ab-f*f

Этот шаблон регулярного выражения показывает, что мы ищем букву а, ноль или несколько букв из нашего класса, и поиск должен закончиться на f. Давайте используем это выражение в Python:

Python

import re
text = ‘abcdfghijk’

parser = re.search(‘a*f’)
print(parser.group()) # ‘abcdf’

1
2
3
4
5

importre

text=’abcdfghijk’

parser=re.search(‘a*f’)

print(parser.group())# ‘abcdf’

В общем, это выражение просмотрит всю переданную ей строку, в данном случае это abcdfghijk.Выражение найдет нашу букву «а» в начале поиска. Затем, в связи с тем, что она имеет класс символа со звездочкой в конце, выражение прочитает остальную часть строки, что бы посмотреть, сопоставима ли она. Если нет, то выражение будет пропускать по одному символу, пытаясь найти совпадения. Вся магия начинается, когда мы вызываем поисковую функцию модуля re. Если мы не найдем совпадение, тогда мы получим None. В противном случае, мы получим объект Match. Чтобы увидеть, как выглядит совпадение, вам нужно вызывать метод group. Существует еще один повторяемый метасимвол, аналогичный *. Этот символ +, который будет сопоставлять один или более раз. Разница с *, который сопоставляет от нуля до более раз незначительна, на первый взгляд.

Символу + необходимо как минимум одно вхождение искомого символа. Последние два повторяемых метасимвола работают несколько иначе. Рассмотрим знак вопроса «?», применение которого выгладит так: “co-?op”. Он будет сопоставлять и “coop” и “co-op”. Последний повторяемый метасимвол это {a,b}, где а и b являются десятичными целыми числами. Это значит, что должно быть не менее «а» повторений, но и не более «b». Вы можете попробовать что-то на подобии этого:

Python

xb{1,4}z

1 xb{1,4}z

Это очень примитивный пример, но в нем говорится, что мы сопоставим следующие комбинации: xbz, xbbz, xbbbz и xbbbbz, но не xz, так как он не содержит «b».

Следующий метасимвол это ^. Этот символ позволяет нам сопоставить символы которые не находятся в списке нашего класса. Другими словами, он будет дополнять наш класс. Это сработает только в том случае, если мы разместим ^ внутри нашего класса. Если этот символ находится вне класса, тогда мы попытаемся найти совпадения с данным символом. Наглядным примером будет следующий: . Так, выражения будет искать совпадения с любой буквой, кроме «а». Символ ^ также используется как анкор, который обычно используется для совпадений в начале строки.

Существует соответствующий якорь для конце строки – «$». Мы потратим много времени на введение в различные концепты применения регулярных выражений. В следующих параграфах мы углубимся в более подробные примеры кодов.

Major new features of the 3.8 series, compared to 3.7

  • PEP 572, Assignment expressions
  • PEP 570, Positional-only arguments
  • PEP 587, Python Initialization Configuration (improved embedding)
  • PEP 590, Vectorcall: a fast calling protocol for CPython
  • PEP 578, Runtime audit hooks
  • PEP 574, Pickle protocol 5 with out-of-band data
  • Typing-related: PEP 591 (Final qualifier), PEP 586 (Literal types), and PEP 589 (TypedDict)
  • Parallel filesystem cache for compiled bytecode
  • Debug builds share ABI as release builds
  • f-strings support a handy specifier for debugging
  • is now legal in blocks
  • on Windows, the default event loop is now
  • on macOS, the spawn start method is now used by default in
  • can now use shared memory segments to avoid pickling costs between processes
  • is merged back to CPython
  • is now 40% faster
  • now uses Protocol 4 by default, improving performance

There are many other interesting changes, please consult the «What’s New» page in the documentation for a full list.

Sets

A set is a set of characters inside a pair of square brackets with a special meaning:

Set Description Try it
Returns a match where one of the specified characters (,
, or ) are
present
Try it »
Returns a match for any lower case character, alphabetically between
and
Try it »
Returns a match for any character EXCEPT ,
, and
Try it »
Returns a match where any of the specified digits (,
, , or ) are
present
Try it »
Returns a match for any digit between
and
Try it »
Returns a match for any two-digit numbers from and Try it »
Returns a match for any character alphabetically between
and , lower case OR upper case
Try it »
In sets, , ,
, ,
, ,
has no special meaning, so means: return a match for any
character in the string
Try it »

Метасимволы нулевой ширины в регулярном выражении.

Некоторые из оставшихся метасимволов, являются утверждениями нулевой ширины. Они не заставляют движок регулярных выражений продвигаться по строке. Они вообще не сравниваются с символами, они просто сообщают движку регулярных выражений о присутствии данного условия в строке или терпят неудачу.

Например — это утверждение, что текущая позиция находится на границе слова. Позиция не изменяется с помощью вообще. Это означает, что утверждения нулевой ширины никогда не должны повторяться, потому что если они совпадают один раз в данном месте, следовательно они могут быть сопоставлены бесконечное число раз.

— Метасимвол :

Метасимвол обозначает чередование, или оператор . Если и являются регулярными выражениями, то выражение будет соответствовать любой строке, которая соответствует либо , либо . Метасимвол имеет очень низкий приоритет, когда чередуются многосимвольные строки. Выражение будет соответствовать или или .

Чтобы сопоставить литерал , используйте или заключите его в символьный класс, как .

— Метасимвол :

Метасимвол — обозначает совпадение с началом строки. Если флаг не установлен, он будет совпадать только с началом строки. В режиме также совпадает сразу после каждой новой строки в строке.

Например, если сопоставить слово только в начале строки, используйте шаблон .

>>> print(re.search('^From', 'From Here to Eternity'))  
# <_sre.SRE_Match object; span=(0, 4), match='From'>
>>> print(re.search('^From', 'Reciting From Memory'))
# None
— Метасимвол :

Метасимвол соответствует концу строки, который определяется как конец строки или любое место, за которым следует символ новой строки.

>>> print(re.search('}$', '{block}'))  
# <_sre.SRE_Match object; span=(6, 7), match='}'>
>>> print(re.search('}$', '{block} '))
# None
>>> print(re.search('}$', '{block}\n'))  
# <_sre.SRE_Match object; span=(6, 7), match='}'>

Чтобы сопоставить литерал , используйте конструкцию или заключите его в класс символов, как .

— Метасимвол :

Метасимвол обозначает обозначает совпадение только с началом строки. Когда режим выключен и фактически одинаковы. В многострочном режиме они различны: по- прежнему совпадает только в начале строки, а может совпадать в любом месте внутри строки, которая следует за символом новой строки .

— Метасимвол :

Совпадает только c концом строки.

— Метасимвол :

Метасимвол обозначает границу слова. Это утверждение с нулевой шириной, которое соответствует только началу или концу слова. Слово определяется как последовательность буквенно-цифровых символов, поэтому конец слова обозначается пробелом или не буквенно-цифровым символом.

Следующий пример соответствует набору букв только тогда, когда это полное слово. Оно не будет совпадать, если набор букв содержится внутри другого слова.

>>> p = re.compile(r'\bclass\b')
>>> print(p.search('no class at all'))  
# <_sre.SRE_Match object; span=(3, 8), match='class'>
>>> print(p.search('the declassified algorithm'))
# None
>>> print(p.search('one subclass is'))
# None

Есть две тонкости, которые должны помнить при использовании этой специальной последовательности. Во-первых, это худшее столкновение между строковыми литералами Python и последовательностями регулярных выражений. В строковых литералах Python это символ — значение ASCII 8. Если не использовать необработанные строки, то Python преобразует \b в и регулярное выражение не будет соответствовать ожидаемому. Следующий пример выглядит так же, как предыдущий RrgExp, но не использует ‘r’ перед строкой шаблона.

>>> p = re.compile('\bclass\b')
>>> print(p.search('no class at all'))
# None
>>> print(p.search('\b' + 'class' + '\b'))  
# <_sre.SRE_Match object; span=(0, 7), match='\x08class\x08'>

Во вторых, внутри символьного класса метасимвол не используется, а представляет символ для совместимости со строковыми литералами Python.

— Метасимвол :

Метасимвол это противоположность . Происходит сопоставление только когда текущая позиция движка не находится на границе слова.

Specify Pattern Using RegEx

To specify regular expressions, metacharacters are used. In the above example, and are metacharacters.

MetaCharacters

Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here’s a list of metacharacters:

[] . ^ $ * + ? {} () \ |

— Square brackets

Square brackets specifies a set of characters you wish to match.

Expression String Matched?
1 match
2 matches
No match
5 matches

Here, will match if the string you are trying to match contains any of the , or .

You can also specify a range of characters using inside square brackets.

  • is the same as .
  • is the same as .
  • is the same as .

You can complement (invert) the character set by using caret symbol at the start of a square-bracket.

  • means any character except a or b or c.
  • means any non-digit character.

— Period

A period matches any single character (except newline ).

Expression String Matched?
No match
1 match
1 match
2 matches (contains 4 characters)

— Caret

The caret symbol is used to check if a string starts with a certain character.

Expression String Matched?
1 match
1 match
No match
1 match
No match (starts with but not followed by )

— Dollar

The dollar symbol is used to check if a string ends with a certain character.

Expression String Matched?
1 match
1 match
No match

— Star

The star symbol matches zero or more occurrences of the pattern left to it.

Expression String Matched?
1 match
1 match
1 match
No match ( is not followed by )
1 match

— Plus

The plus symbol matches one or more occurrences of the pattern left to it.

Expression String Matched?
No match (no character)
1 match
1 match
No match (a is not followed by n)
1 match

— Question Mark

The question mark symbol matches zero or one occurrence of the pattern left to it.

Expression String Matched?
1 match
1 match
No match (more than one character)
No match (a is not followed by n)
1 match

— Braces

Consider this code: . This means at least n, and at most m repetitions of the pattern left to it.

Expression String Matched?
No match
1 match (at )
2 matches (at and )
2 matches (at and )

Let’s try one more example. This RegEx matches at least 2 digits but not more than 4 digits

Expression String Matched?
1 match (match at )
3 matches (, , )
No match

— Alternation

Vertical bar is used for alternation ( operator).

Expression String Matched?
No match
1 match (match at )
3 matches (at )

Here, match any string that contains either a or b

— Group

Parentheses is used to group sub-patterns. For example, match any string that matches either a or b or c followed by xz

Expression String Matched?
No match
1 match (match at )
2 matches (at )

— Backslash

Backlash is used to escape various characters including all metacharacters. For example,

match if a string contains followed by . Here, is not interpreted by a RegEx engine in a special way.

If you are unsure if a character has special meaning or not, you can put in front of it. This makes sure the character is not treated in a special way.

Special Sequences

Special sequences make commonly used patterns easier to write. Here’s a list of special sequences:

— Matches if the specified characters are at the start of a string.

Expression String Matched?
Match
No match

— Matches if the specified characters are at the beginning or end of a word.

Expression String Matched?
Match
Match
No match
Match
Match
No match

— Opposite of . Matches if the specified characters are not at the beginning or end of a word.

Expression String Matched?
No match
No match
Match
No match
No match
Match

— Matches any decimal digit. Equivalent to

Expression String Matched?
3 matches (at )
No match

— Matches any non-decimal digit. Equivalent to

Expression String Matched?
3 matches (at )
No match

— Matches where a string contains any whitespace character. Equivalent to .

Expression String Matched?
1 match
No match

— Matches where a string contains any non-whitespace character. Equivalent to .

Expression String Matched?
2 matches (at )
No match

— Matches any alphanumeric character (digits and alphabets). Equivalent to . By the way, underscore is also considered an alphanumeric character.

Expression String Matched?
3 matches (at )
No match

— Matches any non-alphanumeric character. Equivalent to

Expression String Matched?
1 match (at )
No match

— Matches if the specified characters are at the end of a string.

Expression String Matched?
1 match
No match
No match

Tip: To build and test regular expressions, you can use RegEx tester tools such as regex101. This tool not only helps you in creating regular expressions, but it also helps you learn it.

Now you understand the basics of RegEx, let’s discuss how to use RegEx in your Python code.

Функция поиска

Эта функция ищет первое вхождение шаблона RE в строке с необязательными флагами .

Вот синтаксис для этой функции —

re.search(pattern, string, flags = 0)

Вот описание параметров —

Sr.No. Параметр и описание
1

шаблон

Это регулярное выражение для сопоставления.

2

строка

Это строка, в которой будет производиться поиск в соответствии с шаблоном в любом месте строки.

3

флаги

Вы можете указать разные флаги используя побитовое ИЛИ (|). Это модификаторы, которые перечислены в таблице ниже.

Функция re.search возвращает объект соответствия в случае успеха, но не при ошибке . Мы используем функцию group (num) или groups () объекта match, чтобы получить соответствующее выражение.

Sr.No. Метод и описание объекта соответствия
1

группа (число = 0)

Этот метод возвращает полное совпадение (или конкретный номер подгруппы)

2

группы ()

Этот метод возвращает все подходящие подгруппы в кортеже (пусто, если их не было)

пример

#!/usr/bin/python3
import re

line = "Cats are smarter than dogs";

searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)

if searchObj:
   print ("searchObj.group() : ", searchObj.group())
   print ("searchObj.group(1) : ", searchObj.group(1))
   print ("searchObj.group(2) : ", searchObj.group(2))
else:
   print ("Nothing found!!")

Когда приведенный выше код выполняется, он дает следующий результат —

matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter

macOS users

  • For Python 3.8, we provide one installer: 64-bit-only that works on macOS 10.9 (Mavericks) and later systems.
  • Please read the «Important Information» displayed during installation for information about SSL/TLS certificate validation and the running the «Install Certificates.command».
Version Operating System Description MD5 Sum File Size GPG
Gzipped source tarball Source release 41a5eaa15818cee7ea59e578564a2629 24493475 SIG
XZ compressed source tarball Source release 51b5bbf2ab447e66d15af4883db1c133 18271948 SIG
macOS 64-bit Intel installer Mac OS X for macOS 10.9 and later 2323c476134fafa8b462530019f34394 29843142 SIG
Windows embeddable package (32-bit) Windows 40830c33f775641ccfad5bf17ea3a893 7335613 SIG
Windows embeddable package (64-bit) Windows cff9e470ee6b57c63c16b8a93c586b28 8199294 SIG
Windows help file Windows 678cdc8e46b0b569ab9284be689be807 8592697 SIG
Windows installer (32-bit) Windows 1b5456a52e2017eec31c320f0222d359 27150976 SIG
Windows installer (64-bit) Windows Recommended f69d9c918a8ad06c71d7f0f26ccfee12 28233448 SIG

Regular Expression Modifiers: Option Flags

Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these −

Sr.No. Modifier & Description
1

re.I

Performs case-insensitive matching.

2

re.L

Interprets words according to the current locale. This interpretation affects the alphabetic group (\w and \W), as well as word boundary behavior (\b and \B).

3

re.M

Makes &dollar; match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string).

4

re.S

Makes a period (dot) match any character, including a newline.

5

re.U

Interprets letters according to the Unicode character set. This flag affects the behavior of \w, \W, \b, \B.

6

re.X

Permits «cuter» regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash) and treats unescaped # as a comment marker.

Находим множественные совпадения

До этого момента мы научились только находить первое совпадение в строке. Но что если у вас строка, в которой содержится множество совпадений? Давайте посмотрим, как найти одно:

Python

import re

silly_string = «the cat in the hat»
pattern = «the»

match = re.search(pattern, text)
print(match.group()) # ‘the’

1
2
3
4
5
6
7

importre

silly_string=»the cat in the hat»

pattern=»the»

match=re.search(pattern,text)

print(match.group())# ‘the’

Теперь, как вы видите, у нас есть два экземпляра слова the, но нашли мы только одно. Существует два метода, чтобы найти все совпадения. Первый, который мы рассмотрим, это использование функции findall:

Python

import re

silly_string = «the cat in the hat»
pattern = «the»

a = re.findall(pattern, silly_string)
print(a) #

1
2
3
4
5
6
7

importre

silly_string=»the cat in the hat»

pattern=»the»

a=re.findall(pattern,silly_string)

print(a)#

Функция findall будет искать по всей переданной ей строке, и впишет каждое совпадение в список. По окончанию поиска вышей строки, она выдаст список совпадений. Второй способ найти несколько совпадений, это использовать функцию finditer:

Python

import re

silly_string = «the cat in the hat»
pattern = «the»

for match in re.finditer(pattern, silly_string):
s = «Found ‘{group}’ at {begin}:{end}».format(
group=match.group(), begin=match.start(),
end=match.end())

print(s)

1
2
3
4
5
6
7
8
9
10
11

importre

silly_string=»the cat in the hat»

pattern=»the»

formatch inre.finditer(pattern,silly_string)

s=»Found ‘{group}’ at {begin}:{end}».format(

group=match.group(),begin=match.start(),

end=match.end())

print(s)

Как вы могли догадаться, метод finditer возвращает итератор экземпляров Match, вместо строк, которые мы получаем от findall. Так что нам нужно немного подформатировать результаты перед их выводом. Попробуйте запустить данный код и посмотрите, как он работает.

re.compile(pattern, repl, string)

Следующий метод позволяет собирать регулярные выражения в отдельный объект, а потом использовать его для поиска. Такое решение избавляет от переписывания одних и тех же выражений.

pattern = re.compile('AV')
result = pattern.findall('AV Analytics Vidhya AV')
print result
result2 = pattern.findall('AV is largest analytics community of India')
print result2

Итог:

'AV', 'AV'
'AV'

Итак, мы рассмотрели поиск определённой последовательности символов. Однако бывает, что у нас нет конкретного шаблона, а нам необходимо вернуть набор символов из строки, которая отвечает некоторым правилам (извлечь нужную информацию из строк). В таких ситуациях нам пригодятся специальные символы:

Дополнительную информацию о спецсимволах можно найти в официальной документации.

По материалам «Beginners Tutorial for Regular Expressions in Python».

Performance

Performance is of course the point of this module, so it better perform well.
Regular expressions vary widely in complexity, and the salient feature of RE2 is
that it behaves well asymptotically. This being said, for very simple substitutions,
I’ve found that occasionally python’s regular re module is actually slightly faster.
However, when the re module gets slow, it gets really slow, while this module
buzzes along.

Test Description # total runs re time(s) re2 time(s) % re time regex time(s) % regex time
Findall URI|Email Find list of ‘(*)://(+)(/*)?|(+)@(+)’ 2 19.961 0.336 1.68% 11.463 2.93%
Replace WikiLinks This test replaces links of the form ] to Obama. 100 16.032 2.622 16.35% 2.895 90.54%
Remove WikiLinks This test splits the data by the <page> tag. 100 15.983 1.406 8.80% 2.252 62.43%

And Now for Something Completely Different

trong>Mr. Praline (John Cleese): I wish to complain, British-Railways Person.
Attendant (Terry Jones): I DON’T HAVE TO DO THIS JOB, YOU KNOW!!!
Mr. Praline: I beg your pardon…?
Attendant: I’m a qualified brain surgeon! I only do this job because I like being my own boss!
Mr. Praline: Excuse me, this is irrelevant, isn’t it?
Attendant: Yeah, well it’s not easy to pad these python files out to 150 lines, you know.
Mr. Praline: Well, I wish to complain. I got on the Bolton train and found myself deposited here in Ipswitch.
Attendant: No, this is Bolton.
Mr. Praline: (to the camera) The pet shop man’s brother was LYING!
Attendant: Can’t blame British Rail for that.

Version Operating System Description MD5 Sum File Size GPG
Gzipped source tarball Source release 364158b3113cf8ac8db7868ce40ebc7b 25627989 SIG
XZ compressed source tarball Source release 71f7ada6bec9cdbf4538adc326120cfd 19058600 SIG
macOS 64-bit Intel installer Mac OS X for macOS 10.9 and later 870e851eef2c6712239e0b97ea5bf407 29933848 SIG
macOS 64-bit universal2 installer Mac OS X for macOS 10.9 and later, including macOS 11 Big Sur on Apple Silicon 59aedbc04df8ee0547d3042270e9aa57 37732597 SIG
Windows embeddable package (32-bit) Windows cacf28418ae39704743fa790d404e6bb 7594314 SIG
Windows embeddable package (64-bit) Windows 0b3a4a9ae9d319885eade3ac5aca7d17 8427568 SIG
Windows help file Windows b311674bd26a602011d8baea2381df9e 8867595 SIG
Windows installer (32-bit) Windows b29b19a94bbe498808e5e12c51625dd8 27281416 SIG
Windows installer (64-bit) Windows Recommended 53a354a15baed952ea9519a7f4d87c3f 28377264 SIG

Matching Versus Searching

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).

Example

#!/usr/bin/python3
import re

line = "Cats are smarter than dogs";

matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
   print ("match --> matchObj.group() : ", matchObj.group())
else:
   print ("No match!!")

searchObj = re.search( r'dogs', line, re.M|re.I)
if searchObj:
   print ("search --> searchObj.group() : ", searchObj.group())
else:
   print ("Nothing found!!")

When the above code is executed, it produces the following result −

No match!!
search --> matchObj.group() :  dogs
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *