review20
Pattern与Matcher类
模式匹配就是检索和指定模式匹配的字符串。java提供了专门用来进行模式匹配的Pattern类和Matcher类,这些类在java.util.regex包中。
模式对象是对正则表达式的封装。
如:
Pattern p;
String regex = "(http://|www)\56?\\w+\56{1}\\w+\56{1}\\p{Alpha}+";
p = Pattern.compile(regex);
模式对象pattern调用matcher(CharSequence input)方法返回一个Matcher对象matcher,成为匹配对象,参数input用于给出matcher要检索的字符串。
Matcher matcher = pattern.matcher(input);
Matcher对象matcher可以使用下列方法寻找字符串input中是否有和模式regex匹配的子序列(regex是创建模式对象pattern时使用的正则表达式)。
public boolean find():寻找input和regex匹配的下一子序列,如果成功该方法返回true,否则返回false.
public boolean matches():matcher调用该方法判断input是否完全和regex匹配。
public boolean lookingAt():matcher调用该方法判断从input的开始位置是否有和regex匹配的子序列。若lookingAt()方法返回true,matcher调用start()方法和end方法可以得到lookingAt()方法找到的匹配模式的子序列在input中的开始位置和结束位置。matcher调用group()方法可以返回lookingAt()方法找到的匹配模式的子序列。
public boolean find(int start):matcher调用该方法判断input从参数start指定位置开始是否有和regex匹配的子序列,参数start为0,该方法和lookingAt()的功能相同。
public String replaceAll(String replacement):matcher调用该方法返回将与regex匹配的字符串被参数replacement替换后的字符串。
public String replaceFirst(String replacement):matcher调用该方法可以返回一个字符串,该字符串是通过把input中第1个与模式regex匹配的字符串替换为参数replacement指定的字符串得到的。
上述部分方法的使用情况如下所示:
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class Test10 { public static void main(String[] args) {
// TODO Auto-generated method stub
Pattern p;
Matcher m;
String regex = "(http://|www)\56?\\w+\56{1}\\w+\56{1}\\p{Alpha}+";
p = Pattern.compile(regex);
String s = "新浪:www.sina.cn,央视:http://www.cctv.com,西农:www.nwsuaf.edu.cn,无:www.edu.cn,百度:www.baidu.com";
System.out.println("原字符串是:" + s);
m = p.matcher(s);
while(m.find())
{
String str = m.group();
System.out.println(str);
}
System.out.println("剔除字符串中的网站网址后得到的字符串:");
String result = m.replaceAll("");
System.out.println(result); } }
运行结果如下所示:

review20的更多相关文章
随机推荐
- Python线程包装器
import threading import subprocess import time def need_thread(func, *args, **kwargs): def fun(): pr ...
- Mac 安装Minikube
环境信息: guoguo-MacBook-Pro-3:~ guoguo$ docker versionClient: Version: 17.12.0-ce API version: 1. ...
- [转载]mvc:view-controller
1.重定向 ? 1 <mvc:view-controller path="/" view-name="redirect:/admin/index"/> ...
- uuid的使用
1.mysql中直接使用uuid()函数,可以生成一个随机的uuid 正常的uuid是36位长度的,其中有4个字符是‘-’,在mysql中可以使用replace()函数来替换‘-’ insert in ...
- Centos小脚本(sftp)
sftp用户创建,改变属组,家目录 #!/bin/python import os,sys class sftp_user(object): def __init__(self,user,passwd ...
- Matlab命令合集 妈妈再也不用担心我不会用matlab了
matlab命令 一.常用对象操作:除了一般windows窗口的常用功能键外.1.!dir 可以查看当前工作目录的文件. !dir& 可以在dos状态下查看.2.who 可以查看当前工作空间变 ...
- 每天一个Linux命令(57)rpm命令
rpm是一个功能十分强大的软件包管理系统. (1)用法: 用法: rpm [参数] [包名] (2)功能: 功能: 使得在Linux下安装.升级和删除软 ...
- MySQL数据文件介绍及存放位置
怎样查看MySql数据库物理文件存放位置? 使用命令行查找: show global variables like '%datadir%'; 我查找的位置:C:\ProgramData\MySQL\M ...
- 主攻ASP.NET MVC4.0之重生:使用反射获取Controller的ActionResult
示例代码 public ActionResult TypeOfForName() { Type typeinfo = typeof(CustomerClassController); //typeof ...
- awk中使用shell变量
方法:使用-v参数. 对于多个shell变量使用多个-v 有个关于shell变量中的空格问题: