I'm trying to validate a name with a regular expression in my android app.
So the rules that I have is; only letters, no spaces or anything (a-ö, A-Ö), and only one hyphen.
I have tried but the reg expression language gives my headaches...
I'm trying to validate a name with a regular expression in my android app.
So the rules that I have is; only letters, no spaces or anything (a-ö, A-Ö), and only one hyphen.
I have tried but the reg expression language gives my headaches...
Not that this is the best idea to verify names. But assuming you've settled your requirements, then you can use next example:
if(input.matches("[a-zA-Z]+(\\-[a-zA-Z]+)?")) {
//OK
} else {
//Invalid
}
Several examples I've tested using this page:
String matches?
qwe Yes
qwe- No
qwe-qwe Yes
qwe-qwe- No
qw2e-qwe2 No
qwe-qwe-qwe No
http://developer.android.com/reference/java/util/regex/Pattern.html gives you the basics.
In particular:
[[a-f][0-9]]
shows you can do OR operations.[d-f]
shows you can select ascii rangesIt even tells you:
Most of the time, the built-in character classes are more useful
and explains the \w
and \W
selectors. \w
accepts underlines and digits.
[[A-Z][a-z]-]+
should work. The plus is there to ensure you get at least one character, though if you have a user called -, it's not that great imho.
EDIT:
If you would add the name of your app, I'd make sure not to buy it though. Such laziness can only lead to an app I don't want to install.