在程序开发中,难免会遇到需要匹配、查找、替换、判断字符串的情况发生,而这些情况有时又比较复杂,如果用纯编码方式解决,往往会浪费程序员的时间及精力。因此,学习及使用正则表达式,便成了解决这一矛盾的主要手段。
正则表达式是一种可以用于模式匹配和替换的规范,一个正则表达式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)组成的文字模式,它 用以描述在查找文字主体时待匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。
正则表达式的特点是:
1、灵活性、逻辑性和功能性非常强;
2、可以迅速地用极简单的方式达到字符串的复杂控制。
3、对于刚接触的人来说,比较晦涩难懂。
由于正则表达式主要应用对象是文本,因此它在各种文本编辑器场合都有应用,小到著名编辑器EditPlus,大到Microsoft Word、Visual Studio等大型编辑器,都可以使用正则表达式来处理文本内容。
在Java中,你必须对每一个向前的斜杠(“\”)进行转义处理。图十不是Java的表示形式,所以我们要在每个“\”前面加上一个“\”以免出现编译错误。遗憾的是,转义处理过程很容易出现错误,所以应该小心谨慎。你可以首先输入未经转义处理的正则表达式,然后从左到右依次把每一个“\”替换成“\\”import org.apache.oro.text.regex.MalformedPatternException
import org.apache.oro.text.regex.MatchResult
import org.apache.oro.text.regex.Pattern
import org.apache.oro.text.regex.PatternCompiler
import org.apache.oro.text.regex.PatternMatcher
import org.apache.oro.text.regex.Perl5Compiler
import org.apache.oro.text.regex.Perl5Matcher
public class Zhengze {
public static void main(String[] args) throws MalformedPatternException {
PatternCompiler compiler = new Perl5Compiler()
String str = ",,test,,,,test"
String argexp = ".*,{3}.*"
Pattern pattern = compiler.compile(argexp)
PatternMatcher matcher = new Perl5Matcher()
if(matcher.contains(str,pattern)) {
MatchResult result = matcher.getMatch()
for(int n = 0n <result.length()n++) {
System.out.println(result.group(n))
}
}else{
System.out.println("nothing")
}
}
}