Using regular expressions - documentation for further reference
import re
text = 'gfgfdAAA1234ZZZuijjk'
m = re.search('AAA(.+?)ZZZ', text)
if m:
found = m.group(1)
# found: 1234
or:
import re
text = 'gfgfdAAA1234ZZZuijjk'
try:
found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
# AAA, ZZZ not found in the original string
found = '' # apply your error handling
# found: 1234
Answer from eumiro on Stack OverflowPython: best way to find and extract substring from a string?
The simplest way to extract a substring from a string
regex to extract a substring from a string in python - Stack Overflow
python - Using regex to extract substrings - Stack Overflow
Videos
Using regular expressions - documentation for further reference
import re
text = 'gfgfdAAA1234ZZZuijjk'
m = re.search('AAA(.+?)ZZZ', text)
if m:
found = m.group(1)
# found: 1234
or:
import re
text = 'gfgfdAAA1234ZZZuijjk'
try:
found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
# AAA, ZZZ not found in the original string
found = '' # apply your error handling
# found: 1234
>>> s = 'gfgfdAAA1234ZZZuijjk'
>>> start = s.find('AAA') + 3
>>> end = s.find('ZZZ', start)
>>> s[start:end]
'1234'
Then you can use regexps with the re module as well, if you want, but that's not necessary in your case.
Hello,
I'm learning python from scratch, and I am trying to figure out how to "extract" a substring from a string. So, for instance, let's say I want to extract the word within the parenthesis for each of these three strings.
'xx(hi)xx' 'abc(there)xyz' 'xx(c)xx'
I know I could use slicing, but this would involve three operations, I think. I'm wondering if there's a sort of pattern I can leverage. How do you guys approach this kind of problem?
Thank you in advance for your help. It is most appreciated!
Your regex is mostly correct, you just need to remove EOL(End of Line) $ as in some case like string2 the pattern does not end with a EOL, and have some extra string after the pattern ends.
import re
string1 = 'fgdshdfgsLooking: 3j #123'
string2 = 'Looking: avb456j #13fgfddg'
pattern = r'Looking: (.*?#\d+)'
match1 = re.search(pattern, string1)
match2 = re.search(pattern, string2)
print('String1:', string1, '|| Substring1:', match1.group(0))
print('String2:', string2, '|| Substring2:', match2.group(0))
Output:
String1: fgdshdfgsLooking: 3j #123 || Substring1: Looking: 3j #123
String2: Looking: avb456j #13fgfddg || Substring2: Looking: avb456j #13
should work, also I've matched everything before # lazily by using ? to match as few times as possible, expanding as needed, that is to avoid matching everything upto second #, in case there is a second #followed by few digits in the string somewhere further down.
Live Demo
You need to remove the $ from the regex:
re.search(r'Looking: (.*#\d+)', string1)
If you also want re to return Looking, you'll have to wrap it in parens:
re.search(r'(Looking: (.*#\d+))', string1)
Your last "," was beeing matched due to a greedy search, (.*?) is non greedy. Also the last comma is optional so that needs to be ignored if not present
import re
s = r'"url":"a","meta":"b","url":"c"'
print(re.findall(r'("url"):"(.*?)",?', s))
You must escape the , to avoid including the comma inside the group. Try this:
re.findall(r'(("url" :[^,]*),*)', s)
You can use this regex:
\t[ \t]\+{3}\$\+{3}[ \t]+([^+]+)$
Demo
Python:
import re
dialogue = "L1045 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ They do not!"
>>> re.findall(r' \t[ \t]\+{3}\$\+{3}[ \t]+([^+]+)$', dialogue)
[('BIANCA', 'They do not!')]
You can also split and slice:
>>> re.split(r'[ \t]\+{3}\$\+{3}[ \t]', dialogue)[-2:]
['BIANCA', ' They do not!']
But split and slice does not gracefully fail if +++$+++ is not found; the search pattern above does.
You can do that without re
data = "L1045 +++$+++ u0 +++$+++ m0 +++$+++ BIANCA +++$+++ They do not!"
parts = data.split('+++$+++')
print(parts[-2].strip())
print(parts[-1].strip())
output
BIANCA
They do not!
You need to capture from regex. search for the pattern, if found, retrieve the string using group(index). Assuming valid checks are performed:
>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1) # group(1) will return the 1st capture (stuff within the brackets).
# group(0) will returned the entire matched text.
'my_user_name'
You can use matching groups:
p = re.compile('name (.*) is valid')
e.g.
>>> import re
>>> p = re.compile('name (.*) is valid')
>>> s = """
... someline abc
... someother line
... name my_user_name is valid
... some more lines"""
>>> p.findall(s)
['my_user_name']
Here I use re.findall rather than re.search to get all instances of my_user_name. Using re.search, you'd need to get the data from the group on the match object:
>>> p.search(s) #gives a match object or None if no match is found
<_sre.SRE_Match object at 0xf5c60>
>>> p.search(s).group() #entire string that matched
'name my_user_name is valid'
>>> p.search(s).group(1) #first group that match in the string that matched
'my_user_name'
As mentioned in the comments, you might want to make your regex non-greedy:
p = re.compile('name (.*?) is valid')
to only pick up the stuff between 'name ' and the next ' is valid' (rather than allowing your regex to pick up other ' is valid' in your group.