Python Regex: How Find a Substring in a String

preview_player
Показать описание
↓ Code Available Below! ↓

This video shows how to find and extract substrings within python strings using the regular expressions package. Locating and extracting substrings from larger strings is a common task in text data processing; Python makes it easy to do these sorts of text data processing tasks.

If you find this video useful, like, share and subscribe to support the channel!

**Note** if you want to match a specific substring (such as a specific word) and not a regular expression pattern, just pass that word or substring in as the "pattern" argument.

Code used in this Python Code Clip:

import re

lines = '''
Nappa - What does the scouter say about his power level?
Vegeta - It's over 9000!
Nappa - What 9000? That can't be right. Can it?
'''

string = lines)

first_match

# Extract the matched string from the match:

# Extract the index positions of the start and end:

string = lines)

for match in all_matches:

string = lines)

all_match_list

* Note: YouTube does not allow greater than or less than symbols in the text description, so the code above will not be exactly the same as the code shown in the video! I will use Unicode large < and > symbols in place of the standard sized ones. .

Рекомендации по теме
Комментарии
Автор

Code used in this Python Code Clip:

import re

lines = '''
Nappa - What does the scouter say about his power level?
Vegeta - It's over 9000!
Nappa - What 9000? That can't be right. Can it?
'''

# Use re.search() to match the first instance of a regex

first_match = re.search(pattern = "[0-9]+",
string = lines)

first_match

# Extract the matched string from the match:

first_match.group()

# Extract the index positions of the start and end:

print(first_match.start())
print(first_match.end())

# Use re.finditer() to find all matches:

all_matches = re.finditer(pattern = "[0-9]+",
string = lines)

for match in all_matches:
print(match.group(), match.start(), match.end())

# Use re.findall() to get all matches as a list of strings

all_match_list = re.findall(pattern = "[0-9]+",
string = lines)

all_match_list

DataDaft
Автор

I was looking for this for days! I thought that I can do it somehow without these specific functions so I tried everything for days! LOL! Watched this video and it took me a couple of minutes!
I think a good programmer first is a good Googler! :D Thank you!

tibsyy
Автор

How to use regex in find() function? I need to find position of string I search for. Sometimes I have to use regex.

podunkman
Автор

Wow, Amazing. You make me save a lot of time. Thank you!

nachoeigu
join shbcf.ru