You may use
String patt = "(?<!\\S)\\p{Alpha}+(?!\\S)";
See the regex demo.
It will match 1 or more letters that are enclosed with whitespace or start/end of string locations. Alternative pattern is either (?<!\S)[a-zA-Z]+(?!\S)
(same as the one above) or (?<!\S)\p{L}+(?!\S)
(if you want to also match all Unicode letters).
Details:
(?<!\\S)
- a negative lookbehind that fails the match if there is a non-whitespace char immediately to the left of the current location
\\p{Alpha}+
- 1 or more ASCII letters (same as [a-zA-Z]+
, but if you use a Pattern.UNICODE_CHARACTER_CLASS
modifier flag, \p{Alpha}
will be able to match Unicode letters)
(?!\\S)
- a negative lookahead that fails the match if there is a non-whitespace char immediately to the right of the current location.
See a Java demo:
String s = "test test3 t3st test: word%5 test! testing t[st";
Pattern pattern = Pattern.compile("(?<!\\S)\\p{Alpha}+(?!\\S)");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group(0));
}
Output: test
and testing
.