Code
See regex in use here
(?:^| )[b-hj-z](?= |$)
Usage
See code in use here
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final String regex = "(?:^| )[b-hj-z](?= |$)";
final String string = "there i r u w want to y z go because f g of a matter";
final String subst = "";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
}
}
If you need case-insensitive matching you pass Pattern.CASE_INSENSITIVE
to Patter.compile
.
Results
Input
there i r u w want to y z go because f g of a matter
Output
there i want to go because of a matter
Explanation
(?:^| )
Assert position at the start of the line or match a space literally[b-hj-z]
Match any lowercase ASCII letter excepta
ori
(?= |$)
Positive lookahead ensuring what follows is a space or the end of the line
Working sample code to remove all single letters except “a” and “i”
String resultStr = "there i r u w want to y z go because f g of a matter".replaceAll("(?:^| )[b-hj-z | B-HJ-Z](?= |$)", "");
Explanation: