• Post Reply Bookmark Topic Watch Topic
  • New Topic

Regex question  RSS feed

 
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want to validate a company name field and it can accept only alpha numeric values at the beginning and at the end and can have space or comma or a single quote anywhere else. So I need a regex expression to validate it.Any help is appreciated
Thanks in advance
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's break that requirement up into a few parts:
- start with an alphanumeric character: "^[a-zA-Z0-9]" (using \w also allows _ which is invalid).
- end with an alphanumeric character: "[a-zA-Z0-9]$"
- in between any number of alphanumeric characters, spaces, commas or single quotes: "[a-zA-Z0-9 ,']*"

Now just paste these together (in the order start, in between, end of course) and you get what you want.

This may still be a little too loose, as it allows company names like "A ,,,,''''B", but this is a non-trivial problem, so the solution will also be non-trivial.

Note: instead of "[a-zA-Z0-9]" you can also use one of the following:
- "\\p{Alnum}"; this is equivalent to "[a-zA-Z0-9]"
- "[\\p{L}\\p{Digit}]"; this is not bound to only a-z and A-Z but can also handle Unicode letters, like those with accents.
 
Ranch Hand
Posts: 334
2
Java Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regex is always fun especially if you like to beat your head against the wall because it feels so good when you stop. It's very powerful and a working regex is very efficient but arcane, obscure and difficult to debug are just a few of the family friendly adjectives I use for it.

I have a little program I use to debug my regex's before I put them into use. It started from the Oracle(nee Sun) tutorial on the Java flavor (http://download.oracle.com/javase/tutorial/essential/regex/).
It let's me play with just the regex and run test inputs through it. Nothing special it could be a lot more sophisticated.

It's small enough I attached the source and a jar.

Hope it helps.

Joe
Well I guess can't attach a jar or zip file but the tutorial has a simpler version that can be extended.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!