Reputation: 544
I'd want to know if it's possible to match a regular expression until a particular character (':') but avoiding negative logical expressions like [^:]* cause I'd like it to return None if not matches encountered. See an example of what it's expected:
import re
string='AbcS:sdaf'
pattern='whatever needed' # match all up to :
re.search(pattern, string).group()
'AbcS'
string2='AbcSsdaf'
pattern2='whatever needed' # match all up to :
re.search(pattern2, string2).group()
None
In other post i've seen some answers mencioning pattern='[^:]*' but this is not what I want because returns all the string if there is not a ':' in the string.
Thank you all
Upvotes: 2
Views: 2726
Reputation: 626835
A non-regex way is to split with :
and count the number of splits. If it is more than 1, get the first item, else, return None:
splits = s.split(':')
if len(splits) > 1:
print(splits[0])
else:
print(None)
See this Python demo.
You may also use a regex approach like
^([^:]*):
and grab Group 1 if there is a match. See the regex demo.
Details
^
- start of string([^:]*)
- Capturing group 1: any 0+ chars other than :
:
- a :
char.import re
strs= ['AbcS:sdaf', 'AbcSsdaf']
pattern= re.compile(r'([^:]*):') # re.match requires a match at string start, ^ is redundant
for s in strs:
m = re.match(pattern, s)
if m:
print(m.group(1))
else:
print(m)
Upvotes: 0
Reputation: 848
You need a capturing group:
pattern = '(.*):' # this will match any and all characters up untill ":"
pattern = '([a-zA-Z])*:' # this will match only letters
pattern = '([a-zA-Z0-9])*:' # matches alphanumericals
If you speak the search criteria, you'll easily remember how to recreate it on your own: capture "()" anything "." as many times as possible "*" until you see a semicolon ":".
Most importantly re.search
will return None if there is no ":" in the search string.
Upvotes: 0
Reputation: 10360
Try this regex:
^(?=.*:)[^:]*
Explanation:
^
- asserts the start of the string(?=.*:)
- positive lookahead to make sure that the line contains a :
[^:]*
- matches 0+ occurrences of any character that is not a :
Upvotes: 3