Advertisement
colemar

Build a regex to match a given integer number range

Oct 30th, 2015
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Awk 0.83 KB | None | 0 0
  1. BEGIN {
  2.   MAX=2000
  3.   for (a = 0; a <= MAX; a++) {
  4.     for (b = a; b <= MAX; b++) {
  5.       print "\n"a"-"b
  6.       regex = range2regex(a,b)
  7.       split(regex,r,"|")
  8.       for (i = 1; i in r; i++) print r[i]
  9.     }
  10.   }
  11. }
  12.  
  13. function range2regex(a,z,    k,m,b,r) {
  14.   k = 10
  15.   while (a <= z) {
  16.     while (a > 0 && (m = a%k) == 0) k *= 10
  17.     b = a - m + k - 1
  18.     if (b > z) {
  19.      k /= 10
  20.      break
  21.     }
  22.     r = (r ? r "|" : "") range2charclass(a,b)
  23.     a = b + 1
  24.     k *= 10
  25.   }
  26.   while (a <= z) {
  27.     while ((b = z - (z+1)%k) < a) k /= 10
  28.     r = (r ? r "|" : "") range2charclass(a,b)
  29.     a = b + 1
  30.     k /= 10
  31.   }
  32.   return r
  33. }
  34.  
  35. function range2charclass(a,b,    k,p,q,r) {
  36.   do {
  37.     p = substr(a,++k,1)
  38.     q = substr(b,k,1)
  39.     r = r (p==q ? p : (p+1==q ? "["p""q"]" : "["p"-"q"]"))
  40.   } while (p != "")
  41.   return r
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement