Home > Software design >  How can I split String with regex
How can I split String with regex

Time:10-29

`“Hakan2Ev"-> Hakan 2 Ev
"Hakan2Ev2"-> Hakan 2 Ev 2  , "Ha2Oy2Het3Magara4", "(Ha2Oy2)" ve "(Ha2Oy2)3"
"Ha2Oy2Het3Magara4" -> Ha 2 Oy 2 Het 3 Magara 4
"(Ha2Oy2)12" -> ( Ha 2 Oy 2 ) 12

I just want to split all words starts with uppercase, numbers and parenthesis Im beginner about regex thank you

I tried this but it just split words starts with uppercase

String[] strArray = cumle.split("(?=\\p{Lu})");

CodePudding user response:

You can use

[A-Z][a-z]*|[a-zA-Z] |[0-9] |[^a-zA-Z0-9] 

See the regex demo.

Details:

  • [A-Z][a-z]* - an uppercase letter and then zero or more lowercase letters
  • | - or
  • [a-zA-Z] - one or more letters
  • | - or
  • [0-9] - one or more digits
  • | - or
  • [^a-zA-Z0-9] - one or more chars other than letters or digits.

See the Java demo:

List<String> strs = Arrays.asList("Hakan2Ev", "Hakan2Ev2", "Ha2Oy2Het3Magara4", "(Ha2Oy2)12");
Pattern p = Pattern.compile("[A-Z][a-z]*|[^a-zA-Z] |[0-9] |[^a-zA-Z0-9] ");
for (String str : strs) {
    System.out.println("--- "   str   " ---");
    Matcher m = p.matcher(str);
    while (m.find()) {
        System.out.println(m.group());
    }
}

Output:

--- Hakan2Ev ---
Hakan
2
Ev
--- Hakan2Ev2 ---
Hakan
2
Ev
2
--- Ha2Oy2Het3Magara4 ---
Ha
2
Oy
2
Het
3
Magara
4
--- (Ha2Oy2)12 ---
(
Ha
2
Oy
2
)
12
  • Related