Abin John Thomas
Abin John Thomas

Reputation: 169

How to find a string among many strings in a line

I have a requirement to find the user from the log.

I have a line of code from my log file. One of the strings in the line is a userid. I have the list of all userid also.

Is there any easy way to identify the userid mentioned in the line.

Eg: Calling Business function ProcessSOMBFCommitment_Sourcing from F4211FSEditLine for ND9074524. Application Name [P421002], Version [] (BSFNLevel = 3)

Here, ND9074525 is the user id. My intention is to identify the user from the line.

Other possible userid can be AB9074158, AC9074168, AD9074123, AE9074152

I do not want to loop through all the possible userid. I thought of creating a list of all userid's and find the userid used in line by some method. Not sure if it exists.

Upvotes: 0

Views: 45

Answers (2)

dot.Py
dot.Py

Reputation: 5157

You can use this regex to fetch the user id:

[A-Z]{2}\d{7}

And then check against valid user ids.

Regex Demonstration


Code:

import re

users = ['AB9074158', 'AC9074168', 'AD9074123', 'AE9074152']
s = 'Calling Business function ProcessSOMBFCommitment_Sourcing from F4211FSEditLine for ND9074524. Application Name [P421002], Version [] (BSFNLevel = 3)'

pat = '[A-Z]{2}\d{7}'
user_id = re.search(pat, s).group(0)

print(user_id)

if user_id in users:
    print("User accepted!")
else:
    print("User not accepted")

Output:

'ND9074524'
'User not accepted'

Upvotes: 3

Scott Hunter
Scott Hunter

Reputation: 49883

Use a regex to find all strings that match the pattern of a userid; then you can see if any of them are actual userids.

Upvotes: 1

Related Questions