简体   繁体   中英

JAVA regular expression with space

I have a problem with the following expression:

String REGEX_Miasto_Dwu_Czlonowe="\D+\s\D+";

Pattern pat_Miasto = Pattern.compile(REGEX_Miasto_Dwu_Czlonowe);
Matcher mat_Miasto_Dwu_Czlonowe = pat_Miasto.matcher(adres);

Because the above pattern matches

"80-227 GDAŃSK                              DOSTUDZIENKI 666";
 "83000  PRUSZCZ GDANSKI                     UL. TYSIACLECIA 666"; 

But it only should match this expression : "PRUSZCZ GDANSKI UL. TYSIACLECIA 666";

THX for help.

You got some problems in your regexp.

  1. first you have to change all backslashes to double backslashes but if you have matches it coulde be a copy and paste error
  2. \\D matches non-digits. Was this your intention?

    \\D+\\s\\D+

正则表达式可视化

Debuggex Demo

Therefore you match some non digits followed by one space followed by some non digits .

I think it is more or less by incident that your expression matches.

This could be a solution for your regexp:

^\d+\D+\d+$

正则表达式可视化

Debuggex Demo

If you want to match your second line as a literal , so that only this line matches you could use:

Matcher.quoteReplacement(String s)

to build this kind of expression from a simple String. All control characters are well escaped.

Your regex matches any number of non-digit \\D+ a space \\s then any number of non-digit. So it matches the first string:

80-227 GDAŃSK                              DOSTUDZIENKI 666
//    ^__________\D+_________^^____________\D+_________^
//                           |
//                         a space

I guess you want:

[^\s\d]+\s[^\s\d]+

Any number of non-space/non digit, a space then any number of non-space/non-digit.

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.

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