implement enough of java.util.regex to ensure String methods work for trivial regular expressions

This commit is contained in:
Joel Dice
2009-08-20 11:14:05 -06:00
parent 71f1efc4cb
commit 4c14a9ab66
3 changed files with 184 additions and 28 deletions

View File

@ -1,4 +1,4 @@
/* Copyright (c) 2008, Avian Contributors
/* Copyright (c) 2008-2009, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
@ -11,17 +11,29 @@
package java.util.regex;
/**
* This implementation is a skeleton, useful only for compilation. At runtime it
* is need to be replaced by a working implementation, for example one from the
* Apache Harmony project.
*
* @author zsombor
* This is a work in progress.
*
* @author zsombor and others
*/
public class Matcher {
private final Pattern pattern;
private CharSequence input;
private int start;
private int end;
Matcher(Pattern pattern, CharSequence input) {
this.pattern = pattern;
this.input = input;
}
public boolean matches() {
throw new UnsupportedOperationException();
if (pattern.pattern().equals(input.toString())) {
start = 0;
end = input.length();
return true;
} else {
return false;
}
}
public boolean requireEnd() {
@ -37,15 +49,18 @@ public class Matcher {
}
public Matcher reset() {
throw new UnsupportedOperationException();
return reset(input);
}
public Matcher reset(CharSequence input) {
throw new UnsupportedOperationException();
this.input = input;
start = 0;
end = 0;
return this;
}
public int start() {
throw new UnsupportedOperationException();
return start;
}
public int start(int group) {
@ -69,15 +84,44 @@ public class Matcher {
}
public String replaceAll(String replacement) {
throw new UnsupportedOperationException();
return replace(replacement, Integer.MAX_VALUE);
}
public String replaceFirst(String replacement) {
throw new UnsupportedOperationException();
return replace(replacement, 1);
}
private String replace(String replacement, int limit) {
reset();
StringBuilder sb = null;
int index = 0;
int count = 0;
while (count < limit && index < input.length()) {
if (find(index)) {
if (sb == null) {
sb = new StringBuilder();
}
if (start > index) {
sb.append(input.subSequence(index, start));
}
sb.append(replacement);
index = end;
++ count;
} else if (index == 0) {
return input.toString();
} else {
break;
}
}
if (index < input.length()) {
sb.append(input.subSequence(index, input.length()));
}
return sb.toString();
}
public int end() {
throw new UnsupportedOperationException();
return end;
}
public int end(int group) {
@ -85,11 +129,19 @@ public class Matcher {
}
public boolean find() {
throw new UnsupportedOperationException();
return find(end);
}
public boolean find(int start) {
throw new UnsupportedOperationException();
String p = pattern.pattern();
int i = Pattern.indexOf(input, p, start);
if (i >= 0) {
this.start = i;
this.end = i + p.length();
return true;
} else {
return false;
}
}
public int groupCount() {