对字符串的查找,剪切,替换,提取(正则表达式)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//对字符串的查找,剪切,替换,提取
public class StringAction {
public static void main(String[] args) {
StringAction sa = new StringAction();
System.out.print(sa.action4());
}
public Boolean action1() {// 查询,判断某个字符串里是否有这个字符串
String str = "abcdefgh";
String regex = "a";
Pattern p = Pattern.compile(regex);
// 如果想在查找时忽略大小写,则可以写成pattern p=pattern.compile(regex,pattern.case_insensitive);
Matcher m = p.matcher(str);
return m.find();
}
public String[] action2() {// 将一个字符串根据某个特定符号,生成数组
String str = "xd::abc::cde";
return str.split("::");
}
public String action3() {// 将一个字符串里一个或多个a的地方替换为一个a
String regex = "a+"; // 表示一个或多个a
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher("aaabbced a ccdeaa");
return m.replaceAll("a");
}
public String action4() {// 提取
String regex = ".+\\\\(.+)$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher("c:\\dir1\\dir2\\name.txt\\a");
if (m.find()) {
return m.group(1);
}
return null;
}
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步