您的位置:首页 > 编程语言 > Java开发

Java基础之一组有用的类——使用正则表达式搜索子字符串(TryRegex)

2013-11-24 16:11 776 查看
控制台程序。

正则表达式只是一个字符串,描述了在其他字符串中搜索匹配的模式。但这不是被动地进行字符序列匹配,正则表达式其实是一个微型程序,用于一种特殊的计算机——状态机。状态机并不是真正的机器,而是软件,专门用于解释正则表达式,根据正则表达式隐含的操作分析给定的字符串。

Java中的正则表达式功能通过java.util.regex包中的两个类实现:Pattern类定义了封装正则表达式的对象;Matcher类定义了封装状态机的对象,可以使用给定的Pattern对象搜索特定的字符串。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Arrays;

class TryRegex {
public static void main(String args[]) {
//  A regex and a string in which to search are specified
String regEx = "had";
String str = "Smith, where Jones had had 'had' had had 'had had's";

// The matches in the output will be marked (fixed-width font required)
char[]  marker = new char[str.length()];
Arrays.fill(marker,' ');
//  So we can later replace spaces with marker characters

//  Obtain the required matcher
Pattern pattern = Pattern.compile(regEx);
Matcher m = pattern.matcher(str);

// Find every match and mark it
while( m.find() ){
System.out.println("Pattern found at Start: "+m.start()+" End: "+m.end());
Arrays.fill(marker,m.start(),m.end(),'^');
}

// Show the object string with matches marked under it
System.out.println(str);
System.out.println(marker);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐