gpt4 book ai didi

java - 将 python 正则表达式转换为 java

转载 作者:行者123 更新时间:2023-11-30 07:02:09 24 4
gpt4 key购买 nike

我知道已经有人问过Here但是我想在 java 中使用命名组,就像 Pshemo 建议的那样,但我无法弄清楚我的正则表达式转换出了什么问题:

这是 python 正则表达式:

regexp = re.compile(r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', re.DOTALL | re.MULTILINE)
matches = regexp.findall(content)

这是我的java转换的正则表达式:

String regexp = "(?<delim>[^\\w\\n\\\"'])(?<space> ?)(?<quote>[\\\"']).*?(?=quote)(?=delim)";
Pattern pattern = Pattern.compile(regexp, Pattern.DOTALL | Pattern.MULTILINE);
Matcher matcher = pattern.matcher(content);

我做错了什么?

最佳答案

您将命名反向引用转换为正向前瞻 ( (?P=quote) => (?=quote) ),而您需要 \k<groupname> :

String regex = "(?<delim>[^\\w\n\"'])(?<space> ?)(?<quote>[\"']).*?\\k<quote>\\k<delim>";

测试于OCPSoft regex tester :

enter image description here

关于java - 将 python 正则表达式转换为 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40740867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com