62,614
社区成员
发帖
与我相关
我的任务
分享
public class RegexTestHarness {
public static void main(String[] args) throws IOException {
String regex = null;
boolean fixedRegex = regex != null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
if (!fixedRegex) {
System.out.println("Enter your regex: ");
regex = bufferedReader.readLine();
}
Pattern pattern
= Pattern.compile(regex);
System.out.println("Enter input string to search: ");
Matcher matcher
= pattern.matcher(bufferedReader.readLine());
boolean found = false;
while (matcher.find()) {
System.out.format("I found the text"
+ " \"%s\" starting at "
+ "index %d and ending at index %d.%n",
matcher.group(),
matcher.start(),
matcher.end());
found = true;
}
if (!found) {
System.out.println("No match found.");
}
}
}
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test{
public static void main(String[] args){
String regex = "(|a?)";
String content = "abc";
Matcher matcher = Pattern.compile(regex).matcher(content);
int start = 0;
int end = 0;
while(matcher.find()){
start = matcher.start();
end = matcher.end();
System.out.println(String.format("'%s',start:%d,end:%d",matcher.group(),start,end));
}
System.out.println("---------------------------------------------------");
regex = "a??";
content = "abc";
matcher = Pattern.compile(regex).matcher(content);
start = 0;
end = 0;
while(matcher.find()){
start = matcher.start();
end = matcher.end();
System.out.println(String.format("'%s',start:%d,end:%d",matcher.group(),start,end));
}
}
}