-3

How can I create a regex to match between two characters inclusively?

From the string "bar x12y bar x30y foo" , I want to get x12y and x30y. I tried following

re.findall( "x(.*?)y", "bar x12y bar x30y foo")

and I get 12 and 30, but I would like to include x and y too, how can I do that?

Emmet B
  • 5,341
  • 6
  • 34
  • 47

2 Answers2

1

You can just include the x and y in the capture group. Since your pattern defines only a single group you can leave out the parentheses altogether:

re.findall("x.*?y", "bar x12y bar x30y foo")
a_guest
  • 34,165
  • 12
  • 64
  • 118
0

you can use non capturing groups to achieve your purpose

re.findall(r'x(?:.*?)y', "bar x12y bar x30y foo")

a better regular expression would be

regex: \bx\d+y\b

Vishal Singh
  • 6,014
  • 2
  • 17
  • 33