Wednesday, March 28, 2012

JRegex

@Grapes(
    @Grab(group='net.sourceforge.jregex', module='jregex', version='1.2_01')
)
import jregex.*
//http://jregex.sourceforge.net/gstarted-advanced.html#imatching

String userNameChars="[\\w.\\-]+" //letters, dots, hyphens
String alphaNums="\\w+"
String dot="\\."
Pattern email=new Pattern(userNameChars + "@" + "(?:"+ alphaNums + dot + ")*" + alphaNums)

List ls = ['s@1.com','2@3.com','howdy@d.']

ls.each {
    println email.matcher(it).matches()
}

Pattern re=new Pattern("\\d\\d:\\d\\d") //two digits + colon + two digits
println("Pattern: "+re)

Matcher m=re.matcher()
test(m,"") // true
test(m,"1") // true
test(m,"12") // true
test(m,"1:2") // true
test(m,"12:") // true
test(m,"12:1") // true
test(m,"12:12") // true
test(m,"12:123") // true
test(m,"1:") // false
test(m,"123:1") // false

void test(Matcher m1, String s) {
   m1.setTarget(s)
   println("\""+s+"\" : "+m1.matchesPrefix()) //note: .matchesPrefix()
}

////*Pure Java/Groovy*////
//credit: http://glaforge.appspot.com/article/incomplete-string-regex-matching
List inp = [
    /12:/,/12:1/,/1/,/12:12/ //trues
    ,/1:/,/123:1/ //falses
]

inp.each {
    def matcher = it =~ /\d{2}:\d{2}/
    println matcher.matches() || matcher.hitEnd()
}

println 'done'

No comments:

Post a Comment