Split string in 3 blocks (Text - Number - Other characters) if possible

旧巷老猫 提交于 2021-01-07 02:43:10

问题


I need to divide a string into 3 blocks at most

  • The first block is only for letters
  • The second only numbers
  • The third the remainder

Examples:

Karbwqeaf 11D
Jablunkovska 21/2
Tastoor Nstraat 43
Schzelkjedow
Heajsd 3/5/7 m 344
Lasdasdt seavees 3., 729. tasdasd F 2.
ul. Pasydufasdfa 73k/120

I need to split like this:

Block1: Karbwqeaf
Block2: 11
Block3: D

Block1: Jablunkovska
Block2: 21
Block3: /2

Block1: Tastoor Nstraat
Block2: 43
Block3: 

Block1: Schzelkjedow
Block2: 
Block3: 

Block1: Heajsd
Block2: 3
Block3: /5/7 m 344

Block1: Lasdasdt seavees 3
Block2: 3
Block3: ., 729. tasdasd F 2.

Block1: ul. Pasydufasdfa
Block2: 73
Block3: k/120

Below my code, but I don't know how to do it so that all my requirements are met. Any idea?

List<String> AllAddress = Arrays.asList("Karbwqeaf 11D", "Jablunkovska 21/2", "Tastoor Nstraat 43", "Schzelkjedow", "Heajsd 3/5/7 m 344", "Lasdasdt seavees 3., 729. tasdasd F 2.", "ul. Pasydufasdfa 73k/120");

for (String Address : AllAddress) {
    String block1 = "";
    String block2 = "";
    String block3 = "";
        
    Pattern pattern = Pattern.compile("(.+)\\s(\\d)(.*)");
    Matcher matcher = pattern.matcher(Address);
    if(matcher.matches()) {
        block1 = matcher.group(1);
        block2 = matcher.group(2);
        block3 = matcher.group(3);
        System.out.println("block1 = " + block1);
        System.out.println("block2 = " + block2);
        System.out.println("block3 = " + block3);
    }
}

回答1:


You can use 3 capturing groups, where the second group matches 1 or more digits and the 3rd group matches any character 0+ times.

^([^\d\r\n]+)(?:\h+(\d+)(.*))?$

Explanation

  • ^ Start of string
  • ( Capture group 1
    • [^\d\r\n]+ Match any char except a newline or digit
  • ) Close group 1
  • (?: Non capture group
    • \h+ Match 1+ horizontal whitespace chars
    • (\d+)(.*) Capture 1 or more digits in group 2 and capture 0 or more times any character in group 3
  • )? Close the non capture group and make it optional
  • $ End of string

Regex demo



来源:https://stackoverflow.com/questions/64027691/split-string-in-3-blocks-text-number-other-characters-if-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!