+ 4

Splitting text by whitespaces headache đŸ˜€đŸ˜„

Hello learners!! If somebody can help.... ❓ Why String#split or Pattern#split return one result more on empty string or with trailing whitespaces? đŸ€”đŸ€”đŸ€” "".split("\\s+").length == 1 " ".split("\\s+").length == 0 " Hello learners".split("\\s+").length == 3 " Hello learners ".split("\\s+").length == 3 ❓ There are any regex to solve it? I mean, some using non capture groups or look ahead/behind capture modifiers combination to bypass it. I try it but without success đŸ˜„. E.g.: (?:^\\s+)\\s+ https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/regex/Pattern.html At this moment I hack it doing a trim() before but I wish know other options... mastering on regular expressions. Testcase Template 👇 https://code.sololearn.com/ckmNb74UCnqr/?ref=app Where I want to apply it 👇 https://code.sololearn.com/cd7dRTk2331T/?ref=app

3rd Apr 2021, 10:03 PM
David OrdĂĄs
David OrdĂĄs - avatar
3 Respostas
6th Apr 2021, 9:19 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Coder Kitten thanks for your contributions I update the post description with a TESTCASE template Yes, Is a bit extrange because in StringTokenizer class encourage using String#split but with this mentioned cases aren't the same 😣. https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/StringTokenizer.html Of course because the almost core classes like that, Scanner... uses internally a Matcher and then, you have to pass the contrary regex definition used in a split method) [^\\s]+
4th Apr 2021, 8:48 PM
David OrdĂĄs
David OrdĂĄs - avatar