java如何用正则表达式匹配与提取字符串
作者:wupeigang1 时间:2023-03-13 07:47:13
java.util.regex类支持用正则表达式来匹配和提取字符串,读者可以去官网查看java.util.regex的详细使用方法。
首先给出一个匹配字符串的例子(判断line是否符合格式"GraphType\\s*=\\s*\".+\"\\s*"):
public static boolean isLegalInputLine(String line ) {
Pattern p =Pattern.compile("GraphType\\s*=\\s*\".+\"\\s*");
Matcher m = p.matcher(line);
boolean r =m.matches();
return r;
}
这个函数判断line是否匹配格式"GraphType\\s*=\\s*\".+\"\\*",这里的格式是使用java的正则表达式语法规则书写的。具体的语法规则我提供一个网址:https://wenku.baidu.com/view/e109601f52d380eb62946d75.html?rec_flag=default&mark_pay_doc=2&mark_rec_page=1&mark_rec_position=4&mark_rec=view_r_1&clear_uda_param=1
里面有具体的介绍。
下面给出用正则表达式提取字符串的例子(从s中提取匹配格式"GraphType\\s*=\\s*\".+\"\\s*"的字符串):
public List<String> getString(String s) {
List<String> strs = new ArrayList<String>();
Pattern p = Pattern.compile("GraphType\\s*=\\s*\".+\"\\s*");
Matcher m = p.matcher(s);
while(m.find()) {
strs.add(m.group());
}
return strs;
}
有一款叫做Regex Match Tracer的软件,可以用它来练习书写java的正则表达式。值得注意的是这款软件匹配和提取字符串的结果和java中的有所不同,有时这块软件不能识别的,java可以识别,笔者就碰到过这种情况。
另外对于学过形式语言与自动机的要注意java的语法规则与形式语言与自动机里面的正则语法不同。
附:Java正则取出每一个匹配的字符串
String data = "我的1<if test='case == 1'>1</if>我的2<if test='case == 2'>2</if>";
String regex = "<if test='([\\s\\S]*?)'>([\\s\\S]*?)</if>";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
String group = matcher.group();
System.out.println(group);
}
来源:https://blog.csdn.net/wupeigang1/article/details/80770169
标签:正则表达式,匹配,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pycharm无法安装第三方库的问题及解决方法以scrapy为例(图解)
2022-11-01 20:53:28
![](https://img.aspxhome.com/file/2023/1/66781_0s.png)
由浅入深漫谈margin属性
2007-05-11 17:03:00
![](https://img.aspxhome.com/file/uploadpic/20075/200751117344792.gif)
在Vue中实现添加全局store
2024-05-03 15:12:38
![](https://img.aspxhome.com/file/2023/6/130186_0s.png)
JS的千分位算法实现思路
2023-08-23 22:40:32
MySQL索引下推详细
2024-01-18 10:01:07
![](https://img.aspxhome.com/file/2023/1/129871_0s.jpg)
深入讲解Python中的迭代器和生成器
2021-11-29 05:32:56
![](https://img.aspxhome.com/file/2023/1/72201_0s.jpg)
HTML与CSS在Flash中的应用
2008-01-23 19:13:00
Python 蚁群算法详解
2023-01-03 03:46:25
![](https://img.aspxhome.com/file/2023/1/65971_0s.jpg)
MySQL表自增id溢出的故障复盘解决
2024-01-24 05:00:50
selenium中get_cookies()和add_cookie()的用法详解
2023-10-22 14:27:19
SQL2005 四个排名函数(row_number、rank、dense_rank和ntile)的比较
2024-01-18 02:47:08
![](https://img.aspxhome.com/file/2023/3/108543_0s.jpg)
用python记录运行pid,并在需要时kill掉它们的实例
2023-07-31 17:30:18
python标准库os库的函数介绍
2022-02-26 09:57:15
卸载安装Node.js与npm过程详解
2024-05-13 09:29:58
解决echarts数据二次渲染不成功的问题
2024-04-27 15:56:44
![](https://img.aspxhome.com/file/2023/6/133086_0s.jpg)
Python内建类型int源码学习
2023-07-02 19:22:15
![](https://img.aspxhome.com/file/2023/0/59150_0s.png)
Python导入模块包原理及相关注意事项
2023-01-26 04:46:31
![](https://img.aspxhome.com/file/2023/6/97266_0s.png)
在python带权重的列表中随机取值的方法
2022-05-09 01:44:25
pandas.dataframe按行索引表达式选取方法
2021-10-28 20:26:32
有关perl正则表达式的一些杂项
2023-08-08 01:12:11