10.13. Regex RE Search¶
re.search()
Searches if pattern contains a string
10.13.1. Example¶
Usage of
re.search()
>>> import re
>>>
>>>
>>> def contains(pattern, text):
... if re.search(pattern, text):
... return True
... else:
... return False
>>>
>>>
>>> COMMIT_MESSAGE = 'MYPROJ-1337, MYPROJ-997 removed obsolete comments'
>>> jira_issuekey = r'[A-Z]{2,10}-[0-9]{1,6}'
>>> redmine_number = r'#[0-9]+'
>>>
>>> contains(jira_issuekey, COMMIT_MESSAGE)
True
>>> contains(redmine_number, COMMIT_MESSAGE)
False
>>> import re
>>>
>>>
>>> TEXT = 'We choose to go to the moon.'
>>>
>>> result = re.search(r'moon', TEXT)
>>>
>>> result
<re.Match object; span=(23, 27), match='moon'>
>>>
>>> result.span()
(23, 27)
>>>
>>> result.regs
((23, 27),)
>>>
>>> TEXT[23]
'm'
>>> TEXT[23:27]
'moon'
>>> import re
>>>
>>>
>>> TEXT = 'We choose to go to the moon.'
>>>
>>>
>>> result = re.search(r'Mars', TEXT)
>>>
>>> result.group()
Traceback (most recent call last):
AttributeError: 'NoneType' object has no attribute 'group'
>>>
>>> result = re.search(r'Mars', TEXT)
>>> if result:
... result.group()
>>>
>>>
>>> if result := re.search(r'Mars', TEXT):
... result.group()
10.13.2. Assignments¶
"""
* Assignment: RE Search Astronauts
* Complexity: easy
* Lines of code: 6 lines
* Time: 5 min
English:
1. Use `re.search()` to get start and end position in `TEXT`:
a. Define `a: tuple[int,int]` for 'Neil Armstrong'
b. Define `b: tuple[int,int]` for 'Buzz Aldrin'
c. Define `c: tuple[int,int]` for 'Michael Collins'
d. Define `d: tuple[int,int]` for 'July 21 at 02:56 UTC'
e. Define `e: tuple[int,int]` for 'Tranquility Base'
f. Define `f: tuple[int,int]` for 'Mark Watney'
2. For each element return tuple i.e. `(10, 20)`
3. If element is not present in `TEXT` assign `None`
4. Run doctests - all must succeed
Polish:
1. Użyj `re.search()` aby dostać pozycję startu i końca w `TEXT`:
a. Zdefiniuj `a: tuple[int,int]` dla 'Neil Armstrong'
b. Zdefiniuj `b: tuple[int,int]` dla 'Buzz Aldrin'
c. Zdefiniuj `c: tuple[int,int]` dla 'Michael Collins'
d. Zdefiniuj `d: tuple[int,int]` dla 'July 21 at 02:56 UTC'
e. Zdefiniuj `e: tuple[int,int]` dla 'Tranquility Base'
f. Zdefiniuj `f: tuple[int,int]` dla 'Mark Watney'
2. Dla każdego ciągu znaków zwracaj tuple np. `(10, 20)`
3. Jeżeli ciąg znaków nie jest obecny w `TEXT` przypisz `None`
4. Uruchom doctesty - wszystkie muszą się powieść
Hints:
* `re.Match.span()`
References:
[1] Wikipedia: Apollo 11
URL: https://en.wikipedia.org/wiki/Apollo_11
Year: 2019
Retrieved: 2019-12-14
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> assert type(a) is tuple, 'a must be a tuple'
>>> assert type(b) is tuple, 'b must be a tuple'
>>> assert type(c) is tuple, 'c must be a tuple'
>>> assert type(d) is tuple, 'd must be a tuple'
>>> assert type(e) is tuple, 'e must be a tuple'
>>> assert f is None, 'f must be a None'
>>> assert len(a) == 2, 'a must be a tuple with two elements'
>>> assert len(b) == 2, 'b must be a tuple with two elements'
>>> assert len(c) == 2, 'c must be a tuple with two elements'
>>> assert len(d) == 2, 'd must be a tuple with two elements'
>>> assert len(e) == 2, 'e must be a tuple with two elements'
>>> assert all(type(x) is int for x in a), 'a must be a tuple[int,int]'
>>> assert all(type(x) is int for x in b), 'b must be a tuple[int,int]'
>>> assert all(type(x) is int for x in c), 'c must be a tuple[int,int]'
>>> assert all(type(x) is int for x in d), 'd must be a tuple[int,int]'
>>> assert all(type(x) is int for x in e), 'e must be a tuple[int,int]'
>>> a
(78, 92)
>>> b
(116, 127)
>>> c
(562, 577)
>>> d
(326, 346)
>>> e
(761, 777)
"""
import re
TEXT = ("Apollo 11 was the spaceflight that first landed humans on the Moon. "
"Commander Neil Armstrong and lunar module pilot Buzz Aldrin formed "
"the American crew that landed the Apollo Lunar Module Eagle on "
"July 20, 1969, at 20:17 UTC. Armstrong became the first person to "
"step onto the lunar surface six hours and 39 minutes later on "
"July 21 at 02:56 UTC; Aldrin joined him 19 minutes later. They spent "
"about two and a quarter hours together outside the spacecraft, "
"and they collected 47.5 pounds (21.5 kg) of lunar material to bring "
"back to Earth. Command module pilot Michael Collins flew the command "
"module Columbia alone in lunar orbit while they were on the Moon's "
"surface. Armstrong and Aldrin spent 21 hours, 36 minutes on the "
"lunar surface at a site they named Tranquility Base before lifting "
"off to rejoin Columbia in lunar orbit. ")
# use re.search() to get 'Neil Armstrong' a (start, end) position or None
# type: tuple[int,int] | None
a = ...
# use re.search() to get 'Buzz Aldrin' a (start, end) position or None
# type: tuple[int,int] | None
b = ...
# use re.search() to get 'Michael Collins' a (start, end) position or None
# type: tuple[int,int] | None
c = ...
# use re.search() to get 'July 21 at 02:56 UTC' a (start, end) position or None
# type: tuple[int,int] | None
d = ...
# use re.search() to get 'Tranquility Base' a (start, end) position or None
# type: tuple[int,int] | None
e = ...
# use re.search() to get 'Mark Watney' a (start, end) position or None
# type: tuple[int,int] | None
f = ...
"""
* Assignment: RE Search Moon Speech
* Complexity: easy
* Lines of code: 5 lines
* Time: 8 min
English:
1. Use `re.search()` to find in text [1]
2. Define `result: str` containing paragraph starting with 'We choose to go to the moon'
3. Run doctests - all must succeed
Polish:
1. Użyj `re.search()` do znalezienia w tekscie [1]
2. Zdefiniuj `result: str` zawierający tekst paragrafu zaczynający się od słów "We choose to go to the moon"
3. Uruchom doctesty - wszystkie muszą się powieść
References:
[1] Kennedy, J.F. Moon Speech - Rice Stadium,
URL: http://er.jsc.nasa.gov/seh/ricetalk.htm
Year: 2019
Retrieved: 2019-12-14
Hints:
* All HTML paragraphs starts with `<p>` and ends with `</p>`
* In real life paragraphs parsing is more complex
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> assert type(result) is str, 'result must be a str'
>>> assert not result.startswith('<p>'), 'result cannot start with <p>'
>>> assert not result.endswith('</p>'), 'result cannot end with </p>'
>>> result # doctest: +NORMALIZE_WHITESPACE
'We choose to go to the moon. We choose to go to the moon in this decade
and do the other things, not because they are easy, but because they are
hard, because that goal will serve to organize and measure the best of our
energies and skills,because that challenge is one that we are willing to
accept, one we are unwilling to postpone, and one which we intend to win,
and the others, too.'
"""
import re
TEXT = ("<h1>TEXT OF PRESIDENT JOHN KENNEDY'S RICE STADIUM MOON SPEECH</h1>\n"
"<p>President Pitzer, Mr. Vice President, Governor, "
"CongressmanThomas, Senator Wiley, and Congressman Miller, Mr. Webb, "
"Mr.Bell, scientists, distinguished guests, and ladies and "
"gentlemen:</p><p>We choose to go to the moon. We choose to go to "
"the moon in this decade and do the other things, not because they "
"are easy, but because they are hard, because that goal will serve "
"to organize and measure the best of our energies and skills,because "
"that challenge is one that we are willing to accept, one we are "
"unwilling to postpone, and one which we intend to win, and the "
"others, too.</p><p>It is for these reasons that I regard the "
"decision last year to shift our efforts in space from low to high "
"gear as among the most important decisions that will be made during "
"my incumbency in the office of the Presidency.</p><p>In the last 24 "
"hours we have seen facilities now being created for the greatest "
"and most complex exploration in man's history.We have felt the "
"ground shake and the air shattered by the testing of a Saturn C-1 "
"booster rocket, many times as powerful as the Atlas which launched "
"John Glenn, generating power equivalent to 10,000 automobiles with "
"their accelerators on the floor.We have seen the site where the F-1 "
"rocket engines, each one as powerful as all eight engines of the "
"Saturn combined, will be clustered together to make the advanced "
"Saturn missile, assembled in a new building to be built at Cape "
"Canaveral as tall as a48 story structure, as wide as a city block, "
"and as long as two lengths of this field.</p>")
# use re.search() to get paragraph starting with "We choose..."
# use .group(1) to get the value from re.Match object
# type: str
result = ...
"""
* Assignment: RE Search Time
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min
English:
1. Use regular expressions to check `TEXT` [1]
contains time in UTC (24 hour clock compliant with ISO-8601)
2. Define `result: str` with matched time
3. Use simplified checking `xx:xx UTC`,
where `x` is a digit
4. Text does not contain any invalid date
5. Run doctests - all must succeed
Polish:
1. Użyj wyrażeń regularnych do sprawdzenia czy `TEXT` [1]
zawiera godzinę w UTC (format 24 godzinny zgodny z ISO-8601)
2. Zdefiniuj `result: str` ze znalezionym czasem
3. Użyj uproszczonego sprawdzania: `xx:xx UTC`,
gdzie `x` to dowolna cyfra
4. Tekst nie zawiera żadnej niepoprawnej godziny
5. Uruchom doctesty - wszystkie muszą się powieść
References:
[1] Wikipedia Apollo 11,
URL: https://en.wikipedia.org/wiki/Apollo_11
Year: 2019
Retrieved: 2019-12-14
Hints:
* `re.Match.group()`
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> assert type(result) is str, 'result must be a str'
>>> assert result.endswith('UTC'), 'result must contain timezone'
>>> result
'20:17 UTC'
"""
import re
TEXT = ("Apollo 11 was the spaceflight that first landed humans on the Moon. "
"Commander Neil Armstrong and lunar module pilot Buzz Aldrin formed "
"the American crew that landed the Apollo Lunar Module Eagle on July "
"20, 1969, at 20:17 UTC. Armstrong became the first person to step "
"onto the lunar surface six hours and 39 minutes later on July 21 at "
"02:56 UTC; Aldrin joined him 19 minutes later. They spent about two "
"and a quarter hours together outside the spacecraft, and they "
"collected 47.5 pounds (21.5 kg) of lunar material to bring back to "
"Earth. Command module pilot Michael Collins flew the command module "
"Columbia alone in lunar orbit while they were on the Moon's surface."
"Armstrong and Aldrin spent 21 hours, 36 minutes on the lunar surface"
"at a site they named Tranquility Base before lifting off to rejoin "
"Columbia in lunar orbit.")
# Pattern for searching time with timezone in 24 format, i.e. '23:59 UTC'
# Text does not contain any invalid date
# type: str
pattern = ...
# use re.search() to find pattern in TEXT, get result text
# use .group() to get the value from re.Match object
# type: str
result = ...
"""
* Assignment: RE Search Time
* Complexity: easy
* Lines of code: 4 lines
* Time: 5 min
English:
1. Use regular expressions to check `TEXT` [1]
contains time in UTC (24 hour clock compliant with ISO-8601)
2. Define `result: str` with matched time
3. Use real checking `xx:xx UTC`,
where `x` is a valid digit at the position
4. Text contains invalid date `24:56 UTC`
5. Run doctests - all must succeed
Polish:
1. Użyj wyrażeń regularnych do sprawdzenia czy `TEXT` [1]
zawiera godzinę w UTC (format 24 godzinny zgodny z ISO-8601)
2. Zdefiniuj `result: str` ze znalezionym czasem
3. Użyj poprawnego sprawdzania: `xx:xx UTC`,
gdzie `x` to odpowiedni znak na danym miejscu
4. Tekst zawiera niepoprawną godzinę: `24:56 UTC`
5. Uruchom doctesty - wszystkie muszą się powieść
References:
[1] Wikipedia Apollo 11,
URL: https://en.wikipedia.org/wiki/Apollo_11
Year: 2019
Retrieved: 2019-12-14
Hints:
* `re.Match.group()`
Tests:
>>> import sys; sys.tracebacklimit = 0
>>> assert type(result) is str, 'result must be a str'
>>> assert result.endswith('UTC'), 'result must contain timezone'
>>> result
'02:56 UTC'
"""
import re
TEXT = ("Apollo 11 was the spaceflight that first landed humans on the Moon. "
"Commander Neil Armstrong and lunar module pilot Buzz Aldrin formed "
"the American crew that landed the Apollo Lunar Module Eagle on July "
"20, 1969, at 24:56 UTC. Armstrong became the first person to step "
"onto the lunar surface six hours and 39 minutes later on July 21 at "
"02:56 UTC; Aldrin joined him 19 minutes later. They spent about two "
"and a quarter hours together outside the spacecraft, and they "
"collected 47.5 pounds (21.5 kg) of lunar material to bring back to "
"Earth. Command module pilot Michael Collins flew the command module "
"Columbia alone in lunar orbit while they were on the Moon's surface."
"Armstrong and Aldrin spent 21 hours, 36 minutes on the lunar surface"
"at a site they named Tranquility Base before lifting off to rejoin "
"Columbia in lunar orbit.")
# Pattern for searching time with timezone in 24 format, i.e. '23:59 UTC'
# Text contains invalid date `24:56 UTC`
# type: str
pattern = ...
# use re.search() to find pattern in TEXT, get result text
# use .group() to get the value from re.Match object
# type: str
result = ...