这次给大家带来使用正则表达式对象实现正则获取步骤详解,使用正则表达式对象实现正则获取的注意事项有哪些,下面就是实战案例,一起来看一下。
获取需要使用到正则的两个对象:
使用的是用正则对象pattern 和匹配器matcher。
用法:
范例:
pattern p = pattern.compile(a*b);
matcher m = p.matcher(aaaaab);
boolean b = m.matches();
步骤:
1,先将正则表达式编译成正则对象。使用的是pattern类一个静态的方法。compile(regex);
2,让正则对象和要操作的字符串相关联,通过matcher方法完成,并返回匹配器对象。
3,通过匹配器对象的方法将正则模式作用到字符串上对字符串进行针对性的功能操作
需求:获取由3个字母组成的单词。
public static void getdemo()
{
string str = da jia zhu yi le,ming tian bu fang jia,xie xie!;
//想要获取由3个字母组成的单词。
//刚才的功能返回的都是一个结果,只有split返回的是数组,但是它是把规则作为分隔符,不会获取符合规则的内容。
//这时我们要用到一些正则对象。
string reg = \\b[a-z]{3}\\b;
pattern p = pattern.compile(reg);
matcher m = p.matcher(str);
while(m.find())
{
system.out.println(m.start()+....+m.end());
system.out.println(sub:+str.substring(m.start(),m.end()));
system.out.println(m.group());
}
// system.out.println(m.find());//将规则对字符串进行匹配查找。
// system.out.println(m.find());//将规则对字符串进行匹配查找。
// system.out.println(m.group());//在使用group方法之前,必须要先找,找到了才可以取。
}
校验邮件
public static void checkmail()
{
string mail = abc123@sina.com.cn;
mail = 1@1.1;
string reg = [a-za-z_0-9]+@[a-za-z0-9]+(\\.[a-za-z]+)+;
reg = \\w+@\\w+(\\.\\w+)+;//简化的规则。笼统的匹配。
boolean b = mail.matches(reg);
system.out.println(mail+:+b);
}
网络爬虫 (获取邮箱)
class getmaillist
{
public static void main(string[] args) throws exception
{
string reg = \\w+@[a-za-z]+(\\.[a-za-z]+)+;
getmailsbyweb(reg);
}
public static void getmailsbyweb(string regex)throws exception
{
url url = new url(http://localhost:8080/myweb/mail.html);
urlconnection conn = url.openconnection();
bufferedreader bufin = new bufferedreader(new inputstreamreader(conn.getinputstream()));
string line = null;
pattern p = pattern.compile(regex);
while((line=bufin.readline())!=null)
{
//system.out.println(line);
matcher m = p.matcher(line);
while(m.find())
{
system.out.println(m.group());
}
}
bufin.close();
}
public static void getmails(string regex)throws exception
{
bufferedreader bufr =
new bufferedreader(new filereader(mail.txt));
string line = null;
pattern p = pattern.compile(regex);
while((line=bufr.readline())!=null)
{
//system.out.println(line);
matcher m = p.matcher(line);
while(m.find())
{
system.out.println(m.group());
}
}
bufr.close();
}
}
单词边界匹配器 \b
\b代表一个单词的开始和结束部分,不匹配任何字符
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
使用前端方法实现图片转字符画
js数组方法使用步骤详解
以上就是使用正则表达式对象实现正则获取步骤详解的详细内容。