Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regex Get String Between Two Substrings

First off, I know this may seem like a duplicate question, however, I could find no working solution to my problem.

I have string that looks like the following:

string = "api('randomkey123xyz987', 'key', 'text')"

I need to extract randomkey123xyz987 which will always be between api(' and ',

I was planning on using Regex for this, however, I seem to be having some trouble.

This is the only progress that I have made:

import re
string = "api('randomkey123xyz987', 'key', 'text')"
match = re.findall("\((.*?)\)", string)[0]
print match

The following code returns 'randomkey123xyz987', 'key', 'text'

I have tried to use [^'], but my guess is that I am not properly inserting it into the re.findall function.

Everything that I am trying is failing.


Update: My current workaround is using [2:-4], but I would still like to avoid using match[2:-4].

like image 309
Sakamaki Izayoi Avatar asked Apr 17 '15 15:04

Sakamaki Izayoi


People also ask

How do you get a string between two substrings in Python?

To find a string between two strings in Python, use the re.search() method. The re.search() is a built-in Python method that searches a string for a match and returns the Match object if it finds a match.

How do I extract a string between two delimiters in Python?

Using index() + loop to extract string between two substrings. In this, we get the indices of both the substrings using index(), then a loop is used to iterate within the index to find the required string between them.

How do you get text between two characters in Python?

With Python, you can easily get the characters between two characters using the string index() function and string slicing.

How do you extract a substring from a string in Python regex?

Use re.search() to extract a substring matching a regular expression pattern. Specify the regular expression pattern as the first parameter and the target string as the second parameter. \d matches a digit character, and + matches one or more repetitions of the preceding pattern.


1 Answers

If the string contains only one instance, use re.search() instead:

>>> import re
>>> s = "api('randomkey123xyz987', 'key', 'text')"
>>> match = re.search(r"api\('([^']*)'", s).group(1)
>>> print match
randomkey123xyz987
like image 58
hwnd Avatar answered Sep 19 '22 05:09

hwnd