英文:
Split string in 3 blocks (Text - Number - Other characters) if possible
问题
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("([A-Za-z]+)\\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);
}
}
英文:
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
得分: 2
你可以使用3个捕获组,其中第二个组匹配1个或多个数字,第三个组匹配任意字符0次或多次。
^([^\d\r\n]+)(?:\h+(\d+)(.*))?$
解释
^
字符串的开始(
捕获组 1[^\d\r\n]+
匹配除换行符或数字之外的任意字符
)
关闭 捕获组 1(?:
非捕获组\h+
匹配1个或多个水平空白字符(\d+)(.*)
在捕获组 2中捕获1个或多个数字,在捕获组 3中捕获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+)(.*))?$
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论