-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

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
Expliked
  • 101
  • 10

5 Answers5

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.

CypherX
  • 7,019
  • 3
  • 25
  • 37
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]) 
hack-tramp
  • 366
  • 3
  • 11
1

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

import re
s = "/World/"
new_s = re.sub(r'\W', "", s)
t.novaes
  • 126
  • 2
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
Leo Arad
  • 4,452
  • 2
  • 6
  • 17
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
JvdV
  • 70,606
  • 8
  • 39
  • 70