简体   繁体   English

使用正则表达式而不是 String.split 拆分以逗号分隔的字符串

[英]Splitting string separated with comma with Regex instead of String.split

Is there any way I can split this string using the Pattern and Matcher classes in Java using regex instead of using String.split() ?有什么方法可以使用 Java 中的 Pattern 和 Matcher 类使用正则表达式而不是使用String.split()来分割这个字符串吗?

o_9,o_8,x_7,o_6,o_5

I have tried doing it with "\\\\w" but it just returned one group in m.group() which is o .我试过用"\\\\w"做它,但它只返回了m.group()一组,即o It should have matched everything except the commas.它应该匹配除逗号之外的所有内容。 Could someone help me with this string split?有人可以帮我拆分这个字符串吗?

Take a look at this:看看这个:

String str = "o_9,o_8,x_7,o_6,o_5";
String[] getstr = str.split(',');
String str1 = getstr[0];
String str2 = getstr[1];
String str3 = getstr[2];
String str4 = getstr[3];
String str5 = getstr[4];

I'm not sure where you've gone wrong, but in your reply to AlanMoore's helpful suggestion you said you could only match the first word.我不确定你哪里出错了,但在你对 AlanMoore 有用建议的回复中,你说你只能匹配第一个词。 The code below shows that it matches all the words:下面的代码显示它匹配所有单词:

    String s = "o_9,o_8,x_7,o_6,o_5";
    Pattern p = Pattern.compile("\\w+");
    Matcher m = p.matcher(s);
    while (m.find()) {
        String matchedWord = m.group();
        System.out.println("Matched \"" + matchedWord + "\".");
    }

Output:输出:

Matched "o_9".
Matched "o_8".
Matched "x_7".
Matched "o_6".
Matched "o_5".

For performance, the Pattern should be compiled once - preferably as a private static final near the top of your class.为了提高性能,Pattern 应该编译一次 - 最好作为靠近类顶部的private static final Avoid creating an array of strings (as String.split() does) unless you really need to.除非确实需要,否则避免创建字符串数组(如String.split()所做的那样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM