开发者

Splitting Java string with quotation marks [duplicate]

开发者 https://www.devze.com 2023-02-27 05:41 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Can you recommend a Java library for reading (and possibly writing) CSV files?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Can you recommend a Java library for reading (and possibly writing) CSV files?

I need to split the String in Java. The separator is the space character. String may include the paired quotation marks (with some text and spaces inside) - the whole body inside the paired quotation marks should be considered as the single token. Example:

 
Input:
       token1 "token 2"  token3

Output: array of 3 elements:
         token1
         token 2
         token3  
开发者_JAVA技巧

How to do it? Thanks!


Split twice. First on quotes, then on spaces.


Assuming that the other solutions will not work for you, because they do not properly detect matching quotes or ignore spaces within quoted text, try something like:

private void addTokens(String tokenString, List<String> result) {
    String[] tokens = tokenString.split("[\\r\\n\\t ]+");
    for (String token : tokens) {
        result.add(token);
    }
}

List<String> result = new ArrayList<String>();
while (input.contains("\"")) {
    String prefixTokens = input.substring(0, input.indexOf("\""));
    input = input.substring(input.indexOf("\"") + 1);
    String literalToken = input.substring(0, input.indexOf("\""));
    input.substring(input.indexOf("\"") + 1);

    addTokens(prefixTokens, result);
    result.add(literalToken);
}

addTokens(input, result);

Note that this won't handle unbalanced quotes, escaped quotes, or other cases of erroneous/malformed input.


import java.util.StringTokenizer; 
class STDemo { 
    static String in = "token1;token2;token3"

    public static void main(String args[]) { 

        StringTokenizer st = new StringTokenizer(in, ";"); 

        while(st.hasMoreTokens()) { 
            String val = st.nextToken(); 
            System.out.println(val); 
        } 
    } 
}

this is easy way to string tokenize

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号