-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
  • 4,321
  • 5
  • 30
  • 44

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
  • 25,051
  • 7
  • 38
  • 80
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
  • 5,236
  • 2
  • 15
  • 27