【发布时间】:2023-01-16 22:44:06
【问题描述】:
我几乎编写了整个问题,然后找到了答案,所以无论如何我都会以问答的形式把它放在这里,因为所描述的行为对我来说似乎令人惊讶。
这个正则表达式工作正常并将字符串分成三部分 - 数字部分被字母部分包围:
select regexp_replace('abc12345def', '^(.*?)([0-9]+)(.*)$', '{first="\1" second="\2" third="\3"}');
{first="abc" second="12345" third="def"}
然而,在删除^ 和$ 锚点后,我得到了
select regexp_replace('abc12345def', '(.*?)([0-9]+)(.*)', '{first="\1" second="\2" third="\3"}');
{first="abc" second="1" third=""}2345def
因为第 2 组和第 3 组具有贪婪量词,我希望它们分别匹配 12345 和 def,因此返回相同的字符串。等效的 Java 代码以这种方式运行:
System.out.println("abc12345def".replaceFirst("(.*?)([0-9]+)(.*)", "{first='$1' second='$2' third='$3'}"));
System.out.println("abc12345def".replaceFirst("^(.*?)([0-9]+)(.*)$", "{first='$1' second='$2' third='$3'}"));
{first='abc' second='12345' third='def'}
{first='abc' second='12345' third='def'}
为什么它不起作用?
【问题讨论】:
标签: regex postgresql