正则表达式,用于在csv字符串中查找值

时间:2014-08-13 20:53:57

标签: java regex csv

源字符串:

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)

P.S。核心语言是Java。


回复:"您没有使用专用正则表达式解析器的任何原因?" 答:嗯,我正在使用Java,所以将使用java.util.regex类。根据我所知道的正则表达,大多数情况下它们都是语言中立的,所以我不完全理解你所驾驶的是什么,你能解释一下吗?


回复:"为什么需要正则表达式?您可以在循环中使用单独的contains()调用,这样更容易维护和理解。" 答:我的印象是,如果正确评论,编写良好的正则表达式将执行得更快,更容易阅读。我错了吗?

2 个答案:

答案 0 :(得分:0)

似乎contains()会对此做得很好。您还可以使用StringTokenizer并遍历每个标记,看它是否等于另一个字符串。

如果你必须使用正则表达式,那么这将\,?([^,]+),?\g用于查找CSV中的每个元素。具体来说,检查特定元素是否在字符串中:

String csv = "1,4,test,v,4t,10,20,more"; System.out.println(csv.matches(",?(" + test + "),?"));

编辑:正则表达式不一定更快或更清晰,取决于实现。如果你愿意,我会举一个例子。

答案 1 :(得分:0)

简单高效:)

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