-8

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...

NullUserException
  • 83,810
  • 28
  • 209
  • 234
Mockarutan
  • 442
  • 4
  • 28
  • 4
    Read item 41 here: http://stackoverflow.com/questions/6162484/why-does-modern-perl-avoid-utf-8-by-default/6163129#6163129 – NullUserException Aug 26 '11 at 17:53
  • Not sure if you've tried [this](http://www.regular-expressions.info/tutorial.html) website for regex yet, but it explains pretty well. – Jeffrey Aug 26 '11 at 18:04
  • @NullUserException: it's not Perl it is Java. However, this is an easy regexp he's asking for... – Kheldar Aug 26 '11 at 18:04
  • 2
    @Khedar I am referring to the sentence that says *"Code that believes someone’s name can only contain certain characters is stupid, offensive, and wrong."*, which I fully endorse. – NullUserException Aug 26 '11 at 18:05
  • 2
    Well, I agree, unless said code validates a name in that particular context, a site nickname for example. If you set the rules as "ASCII and hyphens only", that's your right :D – Kheldar Aug 26 '11 at 18:07

2 Answers2

3

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   
inazaruk
  • 74,247
  • 24
  • 188
  • 156
2

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 ranges

It 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.

Volo
  • 28,673
  • 12
  • 97
  • 125
Kheldar
  • 5,361
  • 3
  • 34
  • 63