Java基于正则表达式实现查找匹配的文本功能【经典实例】
本文实例讲述了Java基于正则表达式实现查找匹配的文本功能。分享给大家供大家参考,具体如下:
REMatch.java:
package reMatch; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Frank */ public class REMatch { public static void main(String[] args) { String patt = "Q[^u]\\d+\\."; Pattern r = Pattern.compile(patt); String line = "Order QT300. Now! QT400."; Matcher m = r.matcher(line); while (m.find()) { // group(0)或group()将会返回整个匹配的字符串(完全匹配);group(i)则会返回与分组i匹配的字符 // 这个例子只有一个分组 System.out.println(patt + " matches \"" + m.group(0) + "\" in \"" + line + "\""); System.out.println("start:" + m.start() + " end:" + m.end()); /* 输出: Q[^u]\d+\. matches "QT300." in "Order QT300. Now! QT400." start:6 end:12 Q[^u]\d+\. matches "QT400." in "Order QT300. Now! QT400." start:18 end:24 */ } } }
eclipse运行结果如下图:
REMatchTwoFields.java:
package reMatchTwoFields; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Frank */ public class REMatchTwoFields { public static void main(String[] args) { String inputLine = "Adams,John Quincy"; Pattern r = Pattern.compile("(.*),(.*)"); Matcher m = r.matcher(inputLine); if (!m.matches()) { throw new IllegalArgumentException("Bad Input"); } // 分组0得到的是整个原字符串 for (int i = 0; i < m.groupCount() + 1; i++) { System.out.println("分组" + i + ":" + m.group(i)); /* 输出: 分组0:Adams,John Quincy 分组1:Adams 分组2:John Quincy */ } } }
eclipse运行结果如下图:
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript
正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg
希望本文所述对大家java程序设计有所帮助。
赞 (0)