简体   繁体   English

Java Split Regex Patten字母和数字

[英]Java split regex patten letters and numbers

I want to split this regexp pattern 2 numbers-3 numbers-5 numbers and letter in two part. 我想将此正则表达式模式分为2 numbers-3 numbers-5 numbers and letter两个2 numbers-3 numbers-5 numbers and letter Numbers and "-" one array and the letters in the second array. 数字和“-”一个数组,第二个数组中的字母。

I been trying to figure it out for a while. 我一直试图找出答案。 Hoping I can get some help. 希望我能得到一些帮助。

Here is an example 这是一个例子

"12-123-12345A"    <----- the string 
// I want to split it such that it can be ["12-123-12345","A"]

I tried this 我试过了

"\\d{2}-\\d{3}-\\d{5}" 
// that only give me ["", "A"]

and this 和这个

"(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"
// ["12", "-", "123", "-", "12345", "A"]

\\D matches any non-digit character (including - ). \\D匹配任何非数字字符(包括- )。 You'd better to use [^-\\d] instead to exclude - . 您最好使用[^-\\d]来排除-

String s = "12-123-12345A";
String parts[] = s.split("(?<=\\d)(?=[^-\\d])");
System.out.println(parts[0]); // 12-123-12345
System.out.println(parts[1]); // A

See a demo: http://ideone.com/emr1Kq 观看演示: http : //ideone.com/emr1Kq

尝试这个

String[] a = "12-123-12345A".split("(?<=\\d)(?=\\p{Alpha})");

(\\d{2}-\\d{3}-\\d{5})(\\w) (\\ d {2} - \\ d {3} - \\ d {5})(\\ w)的

You can test it on this website 您可以在此网站上进行测试

http://regexpal.com/ http://regexpal.com/

Here's the java code. 这是Java代码。 note double slash in replace of slash \\ --> \\\\ 注意用双斜杠代替斜杠\\-> \\\\

package com.company;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

// http://stackoverflow.com/questions/22061614
public class Main {

    public static void main(String[] args) {
      Pattern regex = Pattern.compile("(\\d{2}-\\d{3}-\\d{5})(\\w)");
      Matcher matcher = regex.matcher("12-123-12345A");
      matcher.find();
      System.out.println(matcher.group(1));
      System.out.println(matcher.group(2));
    // write your code here
    }
}

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

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