gpt4 book ai didi

Java/正则表达式 : Negate the same character repeated twice:

转载 作者:行者123 更新时间:2023-11-29 09:58:36 26 4
gpt4 key购买 nike

如果我有以下字符串:

--l=Richmond-Hill, NYC --m=5-day --d=hourly

我要匹配组:

--l=Richmond-Hill, NYC

--m=5-day

--d=hourly

我想出了以下正则表达式:

(^--[a-zA-Z]=[^-]*)

当等号后的值没有破折号时,此方法有效。基本上,我如何否定双破折号?

最佳答案

我的猜测是,您可能希望设计一些类似于以下的表达式:

--[a-zA-Z]=.*?(?=--|$)

Demo

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class re{
public static void main(String[] args){

final String regex = "--[a-zA-Z]=.*?(?=--|$)";
final String string = "--l=Richmond-Hill, NYC --m=5-day --d=hourly\n"
+ "--l=Richmond-Hill, NYC\n"
+ "--m=5-day\n"
+ "--d=hourly";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}

}
}

输出

Full match: --l=Richmond-Hill, NYC 
Full match: --m=5-day
Full match: --d=hourly
Full match: --l=Richmond-Hill, NYC
Full match: --m=5-day
Full match: --d=hourly

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


正则表达式电路

jex.im可视化正则表达式:

enter image description here

关于Java/正则表达式 : Negate the same character repeated twice:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57648943/

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