字符串:正则表达式的使用

前端之家收集整理的这篇文章主要介绍了字符串:正则表达式的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


/*
* 2018年3月30日15:53:17
* 代码目的:
* 演示正则表达式java.util.regex中两个类的使用。
* 1, 导入java.util.regex
* 2, 使用static Pattern.compile()方法来编译你的正则表达式,
它会根据你的String类型的正则表达式生成一个Pattern对象。
* 3, 把你想要检索的字符串传入Pattern对象的matcher()方法
* 4, matcher()方法生成一个Matcher对象,有很多功能可用,
* 它的replaceAll()方法能将所有匹配的部分都替换成你传入的参数。
*
* 该程序需要使用命令行参数
* */

  1. //: strings/TestRegularExpression.java
  2. // Allows you to easily try out regular expressions.
  3. // {Args: abcabcabcdefabc "abc+" "(abc)+" "(abc){2,}" }
  4. import java.util.regex.*;
  5. import static net.mindview.util.Print.*;
  6.  
  7. public class TestRegularExpression {
  8. public static void main(String[] args) {
  9. if(args.length < 2) {
  10. print("Usage:\njava TestRegularExpression " +
  11. "characterSequence regularExpression+");
  12. System.exit(0);
  13. }
  14. print("Input: \"" + args[0] + "\"");
  15. for(String arg : args) {
  16. print("Regular expression: \"" + arg + "\"");
  17. Pattern p = Pattern.compile(arg);
  18. Matcher m = p.matcher(args[0]);
  19. /*
  20. * Regular expression: "abc+"
  21. Match "abc" at positions 0-2
  22. Match "abc" at positions 3-5
  23. Match "abc" at positions 6-8
  24. Match "abc" at positions 12-14
  25. 通过该输出,可以看到在字符串匹配一个模式时,会从头开始进行,
  26. 在第一次匹配时,匹配的位置是0--3,而匹配的内容由group()显示
  27. 起始和结束位置由start和end方法显示
  28. 再次进入循环时,匹配从end方法所指向的位置开始进行。
  29. * */
  30. while(m.find()) {
  31. print("Match \"" + m.group() + "\" at positions " +
  32. m.start() + "-" + (m.end() - 1));
  33. }
  34. }
  35. }
  36. } /* Output:
  37. Input: "abcabcabcdefabc"
  38. Regular expression: "abcabcabcdefabc"
  39. Match "abcabcabcdefabc" at positions 0-14
  40. Regular expression: "abc+"
  41. Match "abc" at positions 0-2
  42. Match "abc" at positions 3-5
  43. Match "abc" at positions 6-8
  44. Match "abc" at positions 12-14
  45. Regular expression: "(abc)+"
  46. Match "abcabcabc" at positions 0-8
  47. Match "abc" at positions 12-14
  48. Regular expression: "(abc){2,}"
  49. Match "abcabcabc" at positions 0-8
  50. *///:~

猜你在找的正则表达式相关文章