源字符串:

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

09-10 08:36
查看更多