在定界符内查找特定字符

Find specific char inside delimiter

我有这个字符串:

(40.959953710949506, -74.18210638344726),(40.95891663745299, -74.10606039345703),(40.917472246121065, -74.09582940498359),(40.921752754230255, -74.16397897163398),(40.95248644043785, -74.21067086616523)

我需要抓住括号内的逗号进行进一步处理,我希望分隔组的逗号保留。

假设我想用 FOO 替换目标逗号,结果应该是:

(40.959953710949506 FOO -74.18210638344726),(40.95891663745299 FOO -74.10606039345703),(40.917472246121065 FOO -74.09582940498359),(40.921752754230255 FOO -74.16397897163398),(40.95248644043785 FOO -74.21067086616523)

我想要一个非特定语言的正则表达式。

re.sub与回调函数一起使用:

inp = "(40.959953710949506, -74.18210638344726),(40.95891663745299, -74.10606039345703),(40.917472246121065, -74.09582940498359),(40.921752754230255, -74.16397897163398),(40.95248644043785, -74.21067086616523)"
output = re.sub(r'\((-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)\)', lambda m: r'(' + m.group(1) + r' FOO ' + m.group(2) + r')', inp)
print(output)

这会打印:

(40.959953710949506 FOO -74.18210638344726),(40.95891663745299 FOO -74.10606039345703),(40.917472246121065 FOO -74.09582940498359),(40.921752754230255 FOO -74.16397897163398),(40.95248644043785 FOO -74.21067086616523)

这里的策略是在不同的组中捕获每个元组中的两个数字。然后,我们用 FOO 代替原来的逗号

来连接这两个数字。

您可以只使用 lookaround 来查找前面没有 ) 的所有 ,,如下所示:

(?<!\)),

I don't want some language specific functions for this

上述正则表达式的格式不是特定于语言的,如以下代码片段或 this regex101 snippet:

所示

const x = '(40.959953710949506, -74.18210638344726),(40.95891663745299, -74.10606039345703),(40.917472246121065, -74.09582940498359),(40.921752754230255, -74.16397897163398),(40.95248644043785, -74.21067086616523)';

const rgx = /(?<!\)),/g;

console.log(x.replace(rgx, ' XXX'));

例如:

import re

s = "(40.959953710949506, -74.18210638344726),(40.95891663745299, -74.10606039345703),(40.917472246121065, -74.09582940498359),(40.921752754230255, -74.16397897163398),(40.95248644043785, -74.21067086616523)"
s = re.sub(r",(?=[^()]+\))", " FOO", s)
print(s)

# (40.959953710949506 FOO -74.18210638344726),(40.95891663745299 FOO -74.10606039345703),(40.917472246121065 FOO -74.09582940498359),(40.921752754230255 FOO -74.16397897163398),(40.95248644043785 FOO -74.21067086616523)

我们使用正向预测来仅替换字符串中 ) 之前出现在 ( 之前的逗号。