Splitting a string using Regex in Java

前端 未结 4 1065
别跟我提以往
别跟我提以往 2020-12-16 15:52

Would anyone be able to assist me with some regex.

I want to split the following string into a number, string number

\"810LN15\"

1 metho

4条回答
  •  忘掉有多难
    2020-12-16 16:49

    String.split won't give you the desired result, which I guess would be "810", "LN", "15", since it would have to look for a token to split at and would strip that token.

    Try Pattern and Matcher instead, using this regex: (\d+)|([a-zA-Z]+), which would match any sequence of numbers and letters and get distinct number/text groups (i.e. "AA810LN15QQ12345" would result in the groups "AA", "810", "LN", "15", "QQ" and "12345").

    Example:

    Pattern p = Pattern.compile("(\\d+)|([a-zA-Z]+)");
    Matcher m = p.matcher("810LN15");
    List tokens = new LinkedList();
    while(m.find())
    {
      String token = m.group( 1 ); //group 0 is always the entire match   
      tokens.add(token);
    }
    //now iterate through 'tokens' and check whether you have a number or text
    

提交回复
热议问题