Reputation: 361
i am trying to find specific part of the string using regex or something like that. for example:
string = "hi i am *hadi* and i have &18& year old"
name = regex.find("query")
age = regex.find("query")
print(name,age)
result:
hadi 18
i need the 'hadi' and '18'
Attention: The string is different each time. I need the sentence or words betwee ** and &&
Upvotes: 1
Views: 55
Reputation: 361
this is how i solved my question:
import re
string = "hello. my name is *hadi* and i am ^18^ years old."
name = re.findall(r"\*(.+)\*", string)
age = re.findall(r"\^(.+)\^", string)
print(name[0], age[0])
Upvotes: 0
Reputation: 2670
Try:
import re
string = "hi i am *hadi* and i have &18& year old"
pattern = r'(?:\*|&)(\w+)(?:\*|&)'
print(re.findall(pattern, string))
Outputs:
['hadi', '18']
You could assign re.findall(pattern, string)
to a variable and have a Python list and access the values etc.
Regex demo:
https://regex101.com/r/vIg7lU/1
The \w+
in the regex can be changed to .*?
if there is more than numbers and letters. Example: (?:\*|&)(.*?)(?:\*|&)
and demo: https://regex101.com/r/RIqLuI/1
Upvotes: 1