简体   繁体   中英

Using re.search in Python Regex to separate x and y coordinates

Suppose I have the following segment of LaTex Code:

  & $(-1,1)$
  & $(0,\infty)$

How would I use regex in python in order to separate out the coordinate pair into its x and y components? I want to use re.search for this.

For example, for the above segment I would want to receive:

x: -1 y: 1
x: 0 y: \infty

Currently I am using:

c = map(str,re.findall(r'-?\S',range))
a = c[1]
b = c[3]

However this only matches integers and not the "\\infty" 's I need.

Thank you.

What about:

import re

lines = '''  & $(-1,1)$
  & $(0,\infty)$ '''

matches = re.findall(r'\((.*),(.*)\)', lines)

for (a,b) in matches:
    print "x: %s  y: %s" % (a,b)

Outputs

x: -1  y: 1
x: 0  y: \infty

If you catch some weirdness, consider replacing * with *? to make the matching "not greedy".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM