Search code examples
javaregexgrailsgroovy

Searching Strings containing a regex in createCriteria Method


I'm using Grails for my web app project. I know the createCriteria method can perform search on existing entries in database. Let's say I have a domain "some_domain" which includes a string variable "domain_string". I want to find out all "domain_strings" that contain either a 7-digit or 10-digit number starting with "1" or "7". (e.g. domain_string1 = ".........1234567.......", domain_string2 = ".......7192839265......", etc)

In my code:

some_domain.createCriteria().list() {
   rlike("domain_string", "%/^(1|7){7,10}/%")
}

I've used java regex here and the grails doc tells me that rlike is for regex input. But I can't get the exact output by the code because I'm not familiar with the groovy syntax. Any suggestions for that? Thanks a lot in advance.


Solution

  • You can use

    rlike("domain_string", /([^0-9]|^)[17][0-9]{6}([0-9]{3})?([^0-9]|$)/)
    

    See the regex demo.

    Details:

    • ([^0-9]|^) - either a non-digit char or start of string
    • [17] - 1 or 7
    • [0-9]{6} - any six digits
    • ([0-9]{3})? - an optional occurrence of three digits
    • ([^0-9]|$) - either a non-digit char or end of string.