将python正则表达式转换为java
我知道已经有人问过了,但是我想像Pshemo建议的那样使用java中的命名组,我不知道我的正则表达式转换有什么问题: 以下是python正则表达式:将python正则表达式转换为java,java,python,regex,Java,Python,Regex,我知道已经有人问过了,但是我想像Pshemo建议的那样使用java中的命名组,我不知道我的正则表达式转换有什么问题: 以下是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)
regexp = re.compile(r'(?P<delim>[^\w\n"\'])(?P<space> ?)(?P<quote>["\']).*?(?P=quote)(?P=delim)', re.DOTALL | re.MULTILINE)
matches = regexp.findall(content)
regexp=re.compile(r'(?P[^\w\n“\'])(?P?(?P[“\']).*(?P=quote)(?P=delim'),re.DOTALL | re.MULTILINE)
matches=regexp.findall(内容)
以下是我的java转换regexp:
String regexp = "(?<delim>[^\\w\\n\\\"'])(?<space> ?)(?<quote>[\\\"']).*?(?=quote)(?=delim)";
Pattern pattern = Pattern.compile(regexp, Pattern.DOTALL | Pattern.MULTILINE);
Matcher matcher = pattern.matcher(content);
String regexp=“(?[^\\w\\n\\\”)(?)(?[\\\”).*(?=quote)(?=delim)”;
Pattern=Pattern.compile(regexp,Pattern.DOTALL | Pattern.MULTILINE);
Matcher Matcher=pattern.Matcher(内容);
我做错了什么?您将命名的反向引用转换为正向的lookaheads(
(?p=quote)
=>(?=quote)
),而您需要\k
:
String regex=“(?[^\\w\n\”)(?)(?[\”)。?\\k\\k”;
测试地点:
问题是什么?注意,您将命名的反向引用转换为正向的lookaheads(
(?P=quote)
=>(?=quote)
)谢谢您,它的工作方式似乎比这种方式更好。它应该捕获一行的内容,如“一”、“二”、“三”、“四”、“五”。但是,我不明白,如果删除元素之间的空格,为什么它不起作用:“一”、“二”、“三”、“四”、“五”
。组空格应与空格字符0或1次匹配,为什么在有0个空格时不匹配?您需要将delim
设置为可选,(?[^\w\n']](?)(?)(?[“]]).\k\k
,因为字符串以引号开头。
String regex = "(?<delim>[^\\w\n\"'])(?<space> ?)(?<quote>[\"']).*?\\k<quote>\\k<delim>";