regex - Java split string by whitespace and punctuation but include only punctuation in result -


hello-world how you?

should result in

hello - world how  ? 

this code tried

string str = "hello-world how you?"; arrays.stream(str.split("\\b+")).foreach(system.out::println); 

you can use regex splitting:

string str = "hello-world how you?"; arrays.stream(str.split("\\p{javawhitespace}+|(?=\\p{p})|(?<=\\p{p})")).foreach(system.err::println); 

here \\p{z}+|(?=\\p{p})|(?<=\\p{p}) splits on unicode whitespace or of lookaheads asserts if previous or next character punctuation character.

regex demo

output:

hello - world how ? 

Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -