简体   繁体   English

使用正则表达式在 Java 中拆分字符串

[英]Split String in Java with regex

I am getting an input from the user as a String, input example are like this:我从用户那里得到一个字符串输入,输入示例是这样的:

Hospital name 123-4567   (Hospital name = name, 123-4567=ZIP CODE)
Hospital 123-4567        (Hospital = name, 123-4567=ZIP CODE)
Hospital 33name 123-4567 (Hospital 33name = name, 123-4567=ZIP CODE)
123-4567                 (123-4567=ZIP CODE)
1234567                  (1234567=ZIP CODE)

Now I found a regex to recognize the ZIP CODE: [0-9]{3}[-,ー]?[0-9]{4} (first are 3 number, then 4 number after -,ー) But I want to split the string in 2 parts: name and zip code.现在我找到了一个正则表达式来识别邮政编码: [0-9]{3}[-,ー]?[0-9]{4} (首先是 3 个数字,然后是 -,ー 之后的 4 个数字)但我想要将字符串分成两部分:名称和邮政编码。 If I split with this regex the string: HOSPITAL NAME 123-4567如果我用这个正则表达式拆分字符串:HOSPITAL NAME 123-4567

I get a variable with only: HOSPITAL NAME, and the ZIP CODE isn't "divided" in another variable / list.我得到一个只有:HOSPITAL NAME 的变量,并且邮政编码没有“划分”在另一个变量/列表中。

I have to separate the 2 parts in 2 different variable / list / array, everything is fine.我必须将 2 个部分分成 2 个不同的变量/列表/数组,一切都很好。

Than is not all, in the user inputbox, every character inputted is processed, so I have to recognize the string on every input.并非全部,在用户输入框中,输入的每个字符都被处理,所以我必须识别每个输入的字符串。

If the user start to input: HOSPITAL NAME 3 (I can guess that this 3 is the start of the ZIP CODE or still the name of the hospital, but if the input continue with: HOSPITAL NAME 345-, I'm sure that 345- is the ZIP CODE)如果用户开始输入:HOSPITAL NAME 3(我可以猜测这3是ZIP CODE的开头或者仍然是医院的名称,但如果输入继续:HOSPITAL NAME 345-,我确定345 - 是邮政编码)

Anyone know how to DIVIDE this sting in 2 parts?有谁知道如何将这个刺分成两部分?

Assuming that inputLine is a single line to parse (eg Hospital name 123-4567 )假设inputLine是要解析的单行(例如Hospital name 123-4567

Pattern pattern = Pattern.compile("(?:(.*)\\s+)?(\\d{3}[-ー]?\\d{4})"):
Matcher matcher = pattern.matcher(inputLine);
matcher.matches();
//use matcher.group(1) for the hospital name (e.g. "Hospital name")
//use matcher.group(2) for the zip code (e.g. "123-4567")

This regex will work for your purposes.此正则表达式将适用于您的目的。

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

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