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. If I split with this regex the string: HOSPITAL NAME 123-4567
I get a variable with only: HOSPITAL NAME, and the ZIP CODE isn't "divided" in another variable / list.
I have to separate the 2 parts in 2 different variable / list / array, everything is fine.
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)
Anyone know how to DIVIDE this sting in 2 parts?
Assuming that inputLine
is a single line to parse (eg 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.