gpt4 book ai didi

java - 正则表达式在 csv 字符串中查找值

转载 作者:太空宇宙 更新时间:2023-11-04 14:38:14 24 4
gpt4 key购买 nike

源字符串:

1,4,test,v,4t,10,20,more  

需要使用正则表达式来查看该字符串是否包含这些值中的任何一个。所以问题是:

Does the source string have 1 in it?  Yes
Does the source string have 10 in it? Yes
Does the source string have v in it? Yes

Does the source string have 01 in it? No
Does the source string have va in it? No
Does the source string have test,v in it? (invalid input, so don't have to worry about it)

附注核心语言是Java。

<小时/>

回应:“您不使用专用正则表达式解析器的原因是什么?”答案:嗯,我正在使用 Java,因此将使用 java.util.regex 类。据我所知,正则表达式在很大程度上是语言中立的,所以我不完全理解你的目的,你能解释一下吗?

<小时/>

回应:“为什么需要正则表达式?您可以在循环中使用单独的 contains() 调用,这会更容易维护和理解。”回答:我的印象是,如果注释正确,编写良好的正则表达式将执行得更快并且更易于阅读。我是不是搞错了?

最佳答案

简单高效:)

public class App {

static String answer(int index) {
return index < 0 ? "No" : "Yes";
}

public static void main(String[] args) {
String line = "1,4,test,v,4t,10,20,more";

String[] arr = line.split(",");

Arrays.sort(arr);

System.out.println(String.format("Does the source string have 1 in it? %s", answer(Arrays.binarySearch(arr, "1"))));
System.out.println(String.format("Does the source string have 10 in it? %s", answer(Arrays.binarySearch(arr, "10"))));
System.out.println(String.format("Does the source string have v in it? %s", answer(Arrays.binarySearch(arr, "v"))));
System.out.println(String.format("Does the source string have 01 in it? %s", answer(Arrays.binarySearch(arr, "01"))));
System.out.println(String.format("Does the source string have va in it? %s", answer(Arrays.binarySearch(arr, "va"))));
System.out.println(String.format("Does the source string have test,v in it? %s", answer(Arrays.binarySearch(arr, "test,v"))));

}
}

输出:

Does the source string have 1 in it? Yes
Does the source string have 10 in it? Yes
Does the source string have v in it? Yes
Does the source string have 01 in it? No
Does the source string have va in it? No
Does the source string have test,v in it? No

关于java - 正则表达式在 csv 字符串中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25295935/

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