1

I'm pretty new on grails, I'm having a problem in matches validation using regex. What I wanted to happen is my field can accept a combination of alphanumeric and specific special characters like period (.), comma (,) and dash (-), it may accept numbers (099) or letters only (alpha) , but it won't accept input that only has special characters (".-,"). Is it possible to filter this kind of input using regex? please help. Thank you for sharing your knowledge.

antibry
  • 282
  • 5
  • 22

2 Answers2

4
^[0-9a-zA-Z,.-]*?[0-9a-zA-Z]+?[0-9a-zA-Z,.-]*$

meaning:
  /
  ^          beginning of the string
  [...]*?    0 or more characters from this class (lazy matching)
  [...]+?    1 or more characters from this class (lazy matching)
  [...]*     0 or more characters from this class
  $          end of the string
  /
Flo
  • 1,965
  • 11
  • 18
  • 1
    Good, but since this is for Grails (which is a Java Pattern), you can't use the trailing case-insensitive match. You should either replace it with explicit case matching (`a-zA-Z`), or use the inline flag at the beginning, `(?i)`. – OverZealous Mar 08 '12 at 09:19
  • 1
    Edited. Haven't worked with Java for years. Was sure RegExes were created "/stuff/flags" style. – Flo Mar 08 '12 at 09:25
  • Wow! this one really works! it's like magic! thanks for sharing and for the explanation, I understand it now, thanks to all of you! – antibry Mar 09 '12 at 01:06
1

I think you could match that with a regular expression like this:

".*[0-9a-zA-Z.,-]+.*"

That means:

"." Begin with any character

"*" Have zero or more of these characters

"[0-9a-zA-Z.,-]" Have characters in the range 0-9, a-z, etc, or . or , or -

"+" Have one or more of this kind of character (so it's mandatory to have one in this set)

"." End with any character

"*" Have zero or more of these characters

This is working ok for me, hope it helps!

chm
  • 1,519
  • 13
  • 21
  • Not exactly what I needed because it also accepts other characters other than ".,-" when you input it with alpha numeric characters, but this one also helps me to understand more about regex,Thanks for sharing chm052! – antibry Mar 09 '12 at 01:04