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.
2 Answers
^[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
/
3 Comments
OverZealous
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).Flo
Edited. Haven't worked with Java for years. Was sure RegExes were created "/stuff/flags" style.
antibry
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!
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!
1 Comment
antibry
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!