Home > Software design >  Python Find Word Within A String With Regex
Python Find Word Within A String With Regex

Time:12-14

I want to extract the user ID value from the below list:

In this case, the value '34234234-5sdf23r-2rf234fs-2344s'

['user_id://34234234-5sdf23r-2rf234fs-2344s', 'account://234hjfs8-33']

I am using the following regex to extract everything between "user_id://" and "',"

(?<=user_id://)(.*)(?=',)

See sandbox here: https://regex101.com/r/VM88Lh/1

My Python code is as follows:

user_id = ['user_id://34234234-5sdf23r-2rf234fs-2344s', 'account://234hjfs8-33']
x = re.findall(r"(?<=user_id://)(.*)(?=',)", user_id)
print(x)

Any help on how to extract this value would be appreciated.

CodePudding user response:

IF the format is constant the below code will serve you.
Using rpartition looks like a clean way to do it. (Thanks @Tomerikoo)

lst  = ['user_id://34234234-5sdf23r-2rf234fs-2344s', 'account://234hjfs8-33']
_id = lst[0].rpartition('/')[-1]
print(_id)

outout

34234234-5sdf23r-2rf234fs-2344s

CodePudding user response:

If it is constant to where user_id:// is always in the first element of the user_id list:

user_id = ['user_id://34234234-5sdf23r-2rf234fs-2344s', 'account://234hjfs8-33']
id = user_id[0][10:]
print(id)
  • Related