PageRenderTime 44ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/src/sys/java/fan/sys/Regex.java

https://bitbucket.org/bedlaczech/fan-1.0
Java | 94 lines | 54 code | 18 blank | 22 comment | 10 complexity | bce47a673863048a6fc9b934042ae711 MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  1. //
  2. // Copyright (c) 2007, Brian Frank and Andy Frank
  3. // Licensed under the Academic Free License version 3.0
  4. //
  5. // History:
  6. // 26 Dec 07 Brian Frank Creation
  7. //
  8. package fan.sys;
  9. import java.util.regex.*;
  10. /**
  11. * Regex
  12. */
  13. public final class Regex
  14. extends FanObj
  15. {
  16. //////////////////////////////////////////////////////////////////////////
  17. // Constructors
  18. //////////////////////////////////////////////////////////////////////////
  19. public static Regex fromStr(String pattern)
  20. {
  21. return new Regex(pattern);
  22. }
  23. public static Regex glob(String pattern)
  24. {
  25. StringBuilder s = new StringBuilder();
  26. for (int i=0; i<pattern.length(); ++i)
  27. {
  28. int c = pattern.charAt(i);
  29. if (FanInt.isAlphaNum(c)) s.append((char)c);
  30. else if (c == '?') s.append('.');
  31. else if (c == '*') s.append('.').append('*');
  32. else s.append('\\').append((char)c);
  33. }
  34. return new Regex(s.toString());
  35. }
  36. Regex(String source)
  37. {
  38. this.source = source;
  39. this.pattern = Pattern.compile(source);
  40. }
  41. //////////////////////////////////////////////////////////////////////////
  42. // Identity
  43. //////////////////////////////////////////////////////////////////////////
  44. public final boolean equals(Object obj)
  45. {
  46. if (obj instanceof Regex)
  47. return ((Regex)obj).source.equals(this.source);
  48. else
  49. return false;
  50. }
  51. public final int hashCode() { return source.hashCode(); }
  52. public final long hash() { return FanStr.hash(source); }
  53. public String toStr() { return source; }
  54. public Type typeof() { return Sys.RegexType; }
  55. //////////////////////////////////////////////////////////////////////////
  56. // Regular expression
  57. //////////////////////////////////////////////////////////////////////////
  58. public boolean matches(String s)
  59. {
  60. return pattern.matcher(s).matches();
  61. }
  62. public RegexMatcher matcher(String s)
  63. {
  64. return new RegexMatcher(pattern.matcher(s));
  65. }
  66. public List split(String s) { return split(s, 0L); }
  67. public List split(String s, long limit)
  68. {
  69. return new List(pattern.split(s, (int)limit));
  70. }
  71. //////////////////////////////////////////////////////////////////////////
  72. // Fields
  73. //////////////////////////////////////////////////////////////////////////
  74. private String source;
  75. private Pattern pattern;
  76. }