-2

I need to find the string in between two other strings. How could I do this?

string = "vHELLOv"

Finding "HELLO" which is in between of two lowercase "v"'s

Another example could be:

string = "/World/"

Finding "World" in the middle of the two "/"s

3
  • 1
    I suggest to look at regexes (re module) Commented Jun 3, 2020 at 7:50
  • 1
    Please update your question with the code you have tried. Commented Jun 3, 2020 at 7:50
  • In case there is just one character arround: "vHELLOv"[1:-1] Commented Jun 3, 2020 at 7:52

5 Answers 5

3

Try this. Use regex (regular expression) library for pattern matching.

import re

# 1st pattern: vHELLOv
re.findall(r"v(.*?)v", "vHELLOv")


# 2nd pattern: /HELLO/
re.findall(r"/(.*?)/", "/HELLO/")

## NOTE: For regex in python you do not have to escape / with a \. 
#        But, if you want to use a similar regex universally elsewhere, 
#        consider escaping each / with a \.
#
#        Example: r"/(.*?)/" ==> r"\/(.*?)\/"

EDIT: Added lazy quantifier .*? instead of .* inside the () as suggested by Jan.

Sign up to request clarification or add additional context in comments.

Comments

1

If you are talking about two identical strings surrounding another, you can use the split method:

string = "vHELLOv"
surrounder = "v"
x = string.split(surrounder)

print(x[1]) 

Comments

1

To remove punctuation, you could use the following regex expression in Python:

import re
s = "/World/"
new_s = re.sub(r'\W', "", s)

Comments

0

You can do it in various ways as

 import re

 text = "vHELLOv" #or txt = "/World/"
 re.match(r"(v|\/)(\w*)(v|\/)", text).group(2)
 or
 re.search(r"(v|\/)(\w*)(v|\/)", text).group(2)

This is the regex methods You can do it also with string replace as

txt.replace(txt[0], "") if txt[0] == txt[-1] else txt

Comments

0

"Another example could be" - Just those words made me think you are not only interested in v or / but any type of character that surrounds a string of interest. Therefor you could try a pattern like:

^(.)(.+)\1$

Or if you want to define the possibilities:

^([\/v])(.+)\1$

This way you would capture the first character in a capture group that you can refer to later down the line. You don't need to distinquish between v or / or any character perse. Now grab group 2 from a search result, e.g.:

import re
s = 'vHELLOv'
print(re.search(r'^(.)(.+)\1$', s).group(2))

returns:

HELLO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.