I've been struggling my mind for the past couple of hours in order to get the following behaviour in a sentence of characters:
John is $@^&%$#@&$^12(random chars...) - match
John is $@^&%$#@&$^12(random chars...) - match (some spaces at the end)
John is $@^&%$#@&$^12(random chars...) - unmatch (some spaces at the beginning)
I could not find any answer to get the right regex to be used in Java for a filter in edit text. Must specify that I am not allowed to change project setting therefore some errors pop-up such as:
'\s' and '\' escape sequences are not supported at language level '8'
Illegal escape character in string literal
Here are a few variants that I tried:
"^[^ ]+.+"
"^[a-zA-Z!@#$%^&*()_+-={};',.<>?/:][ ]*.*"
"^[a-zA-Z0-9_ ]*$"
"^[^ ]+( .+)*$"
"^\\w+( \\w+)*$"
"^- (\\w+( \\w+)*)$"
"^[a-zA-Z0-9_][a-zA-Z0-9_ ]*[a-zA-Z0-9_]$"
"^[^ ]+[\\s]*"
"^[^-\\s][\w\s-]+$"
None of them works
EDIT
Here is all the code:
final EditText nameInput = line2.findViewById(R.id.input_value);
nameInput.setFilters(new InputFilter[] {new NoSpaceStartInputFilter()});
private static class NoSpaceStartInputFilter implements InputFilter {
private Pattern mPattern;
public NoSpaceStartInputFilter() {
mPattern = Pattern.compile("^[^ ]+.+");
mPattern = Pattern.compile("^[a-zA-Z!@#$%^&*()_+-={};',.<>?/:][ ]*.*");
mPattern = Pattern.compile("^[a-zA-Z0-9_ ]*$");
mPattern = Pattern.compile("^[^ ]+( .+)*$");
mPattern = Pattern.compile("^\\w+( \\w+)*$");
mPattern = Pattern.compile("^- (\\w+( \\w+)*)$");
mPattern = Pattern.compile("^[a-zA-Z0-9_][a-zA-Z0-9_ ]*[a-zA-Z0-9_]$");
mPattern = Pattern.compile("^[^ ]+[\\s]*");
mPattern = Pattern.compile("^[^-\\s][\w\s-]+$");
mPattern = Pattern.compile("^(?!\\s+\\S)\\S*\\s.*");
}
@Override
public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
Matcher matcher = mPattern.matcher(charSequence);
if (!matcher.matches())
return "";
return null;
}
}