Home > Software design >  Python extract string in a phrase
Python extract string in a phrase

Time:02-02

I have a python string that comes in a standard format string and i want to extract a piece of that string.

The string come as such:

logs(env:production service:FourDS3.Expirer @Properties.NewStatus:(ChallengeAbandoned OR Expired) @Properties.Source:Session).index(processing).rollup(count).by(@Properties.AcsInfo.Host).last(15m) > 60

I want to extract everything between logs(), that is i need to get this env:production service:FourDS3.Expirer @Properties.NewStatus:(ChallengeAbandoned OR Expired) @Properties.Source:Session

I have tried the below regex but it's not working:

result = re.search('logs((. ?)).', message.strip())
return result.group(1)

result = re.search('logs((.*?)).', message.strip())
return result.group(1)

Can someone please help me ?

CodePudding user response:

If that input string is always in exactly the same format, then you could use the fact that the closing bracket for logs is followed by a .:

original = '''logs(env:production service:FourDS3.Expirer @Properties.NewStatus:(ChallengeAbandoned OR Expired)@Properties.Source:Session).index(processing).rollup(count).by(@Properties.AcsInfo.Host).last(15m) > 60'''
extracted = original.split('logs(')[1].split(').')[0]
print(extracted)

Which gives you this, without the need for regex:

'env:production service:FourDS3.Expirer @Properties.NewStatus:(ChallengeAbandoned OR Expired)@Properties.Source:Session'

CodePudding user response:

You can achieve the result via regex like this:

input = "logs(env:production service:FourDS3.Expirer @Properties.NewStatus:(ChallengeAbandoned OR Expired) @Properties.Source:Session).index(processing).rollup(count).by(@Properties.AcsInfo.Host).last(15m) > 60"
pattern = r'logs\((?P<log>.*)\).index'
print(re.search(pattern, input).group('log'))
# which prints:
# env:production service:FourDS3.Expirer @Properties.NewStatus:(ChallengeAbandoned OR Expired) @Properties.Source:Session

The ?<P> is a named group, which you access by calling group with the name specified inside <>

  •  Tags:  
  • Related