如果可能,将字符串拆分为 3 个块(文本 - 数字 - 其他字符) [英] Split string in 3 blocks (Text - Number - Other characters) if possible

查看:53
本文介绍了如果可能,将字符串拆分为 3 个块(文本 - 数字 - 其他字符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最多需要将一个字符串分成 3 个块

I need to divide a string into 3 blocks at most

  • 第一个块仅用于字母
  • 第二个数字
  • 余数的第三个

示例:

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

我需要这样拆分:

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);
    }
}

推荐答案

您可以使用 3 个捕获组,其中第二组匹配 1 个或多个数字,第三组匹配任意字符 0 次以上.

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+)(.*))?$

说明

  • ^ 字符串开始
  • ( 捕获组 1
    • [^\d\r\n]+ 匹配除换行符或数字以外的任何字符
    • ^ Start of string
    • ( Capture group 1
      • [^\d\r\n]+ Match any char except a newline or digit
      • \h+ 匹配 1+ 个水平空白字符
      • (\d+)(.*) 捕获组2中的1个或多个数字并捕获组3中的任意字符0次或多次>
      • \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

      正则表达式演示

      这篇关于如果可能,将字符串拆分为 3 个块(文本 - 数字 - 其他字符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆