使用
RegexString.with(string).pattern(pattern).start() + 后续操作(matches,find或者是replace)
源码
package com;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexString {
private String string;
private Pattern pattern;
private Matcher matcher;
////////////////////// Constructor //////////////////////
public RegexString(String str) {
setString(Objects.requireNonNull(str));
}
////////////////////// Normal Method //////////////////////
public RegexString pattern(String regex) {
setPattern(Pattern.compile(regex));
return this;
}
public RegexString pattern(String regex, int flags) {
setPattern(Pattern.compile(regex, flags));
return this;
}
public RegexString start() {
setMatcher(pattern.matcher(string));
return this;
}
public String replace(String replacement) {
return getMatcher().replaceAll(replacement);
}
public boolean matches() {
return getMatcher().matches();
}
public boolean find() {
return getMatcher().find();
}
public String matchString() {
return getMatcher().group();
}
public int matchStart() {
return getMatcher().start();
}
public int matchEnd() {
return getMatcher().end();
}
////////////////////// Static Method //////////////////////
public static RegexString with(String str) {
return new RegexString(str);
}
////////////////////// Getter & Setter //////////////////////
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public Pattern getPattern() {
return pattern;
}
public void setPattern(Pattern pattern) {
this.pattern = pattern;
}
public Matcher getMatcher() {
return matcher;
}
public void setMatcher(Matcher matcher) {
this.matcher = matcher;
}
}
示例
package com;
public class Main {
public static void main(String args[]) {
// 查找文本
{
String src = "This is my small example string which I'm going to use for pattern matching.";
RegexString string = RegexString.with(src).pattern("\w+").start();
while (string.find()) {
System.out.println(string.matchStart() + "," + string.matchEnd() + " : " + string.matchString());
}
}
// 匹配
{
String src = "This is my small example string which I'm going to use for pattern matching.";
if (RegexString.with(src).pattern("^This.+$").start().matches()) {
System.out.println("Yes");
}
}
// 替换文本
{
String src = "This is my small example string which I'm going to use for pattern matching.";
System.out.println(RegexString.with(src).pattern("\w+").start().replace("Regex"));
}
// 去掉字符串首尾的空格,以及字符串中间多余的字符串
{
String src = " This is my small example string which I'm going to use for pattern matching. ";
String tmp = RegexString.with(src).pattern("^\s+|\s+$").start().replace("");
String des = RegexString.with(tmp).pattern("\s+").start().replace(" ");
System.out.println(""" + des + """);
}
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持考高分网!



