0

In an application which I continue to develop, I need to find all the space separated chars, which is a word under normal circumstances. Let me give you an example.

This is an e x a m p l e sentence.

In the above example, I need to find the e x a m p l e.

I've made my search through the SO, but couldn't find a solution to my problem. Most of the similar problems are trying to regex a String and mask some of the chars in it.

Any help will be greatly appreciated.

Thanks in advance.

Prometheus
  • 1,522
  • 3
  • 23
  • 41

2 Answers2

2

You can use

\b(?:\w )+\w\b

That is - a word boundary, followed by (repeated) single characters and spaces, followed by another character and a word boundary.

https://regex101.com/r/gOXP2w/1

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1
List<String> letters = Arrays.stream(yourString.split(" ").filter(part->part.length()==1).collect(Collectors.toList());

Step-by-step explanation:

Take your source string, split it at every blank character and put all resulting strings in a string array:

String[] parts = yourString.split(" ");

The resulting string array currently also contains strings having more than 1 character. So you have to iterate over these strings and remove all those strings that have more than 1 character, so that in the end only strings with a single character will remain. Java8 Streams API allows you to do so in a descriptive way (Stream<T> filter(Predicate<? super T> predicate) method), so let's transform the string array to a stream of strings:

Stream<String> partsStream = Arrays.stream(parts);

Now you can filter the stream by calling Stream<T> filter(Predicate<? super T> predicate) method on this stream - all matching strings will be returned as a new stream. Quick note on predicates: Java interface java.util.function.Predicate is a so called 'functional interface', functional interfaces have only one boolean-valued method - in case of Predicate this single method is called boolean test(T t). So for every item in the stream this test(...) method will by called to decide wether the item matches a certain condition. A short and descriptive implementation of this predicate can be a so called lambda expression (Java8+):

// for filtering in the next line, only keep strings with 1 character!
Predicate<String> filterCondition = item -> item.length() == 1;

Stream<String> filteredStream = partsStream.filter(filterCondition);

In the end you 'collect' all strings inside the filtered stream into a java.util.List of type java.lang.String:

List<String> letters = filteredStream.collect(Collectors.toList());