正则表达式初探(Java String regex Grok)

前端之家收集整理的这篇文章主要介绍了正则表达式初探(Java String regex Grok)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

什么是正则表达式?不同的网站的解释略有差别。在此我引用 wikipedia 的版本:In theoretical computer science and formal language theory,a regular expression (sometimes called a rational expression) is a sequence of characters that define a search pattern,mainly for use in pattern matching with strings,or string matching,i.e. “find and replace”-like operations. 直译过来就是:一个字符的序列,它定义了一个搜索模式

很多编程语言内置了regex ( regular expression 的缩写 ) 的功能(都是一些大神写的算法,我们凡人学会使用就行了),不同的语言在语法定义上略有不同。我初次学习正则表达式,是基于 java 的正则表达式。

来几个有用的网址。

Java 正则表达式中文学习网站
Java 正则表达式 English 学习网站
在线测试 Grok 正则表达式网站
Grok 正则表达式学习
BM 算法详解,传说中的 Ctrl + F ?


talk is cheap,show me the code

String 的 regex

String 有 4 个方法用到了 regex : matches( ),split( ),replaceFirst( ),replaceAll( )

  1. package regextest;
  2.  
  3. public class RegexTestStrings
  4. {
  5. public final static String EXAMPLE_TEST =
  6. "This is my small example string which I'm going to use for pattern matching .";
  7.  
  8. public static void main(String[] args)
  9. {
  10. // 判断是否是:第一个字符是‘word字符’的字符串
  11. System.out.println(EXAMPLE_TEST.matches("\\w.*"));
  12.  
  13. // 用 white spaces 拆开字符串,返回拆开后的String数组
  14. String[] splitString = (EXAMPLE_TEST.split("\\s+"));
  15. System.out.println(splitString.length);
  16. for (String string : splitString)
  17. {
  18. System.out.println(string);
  19. }
  20.  
  21. // 把符合正则式"\\s+"的字符串,全部替换成"才"
  22. System.out.println(EXAMPLE_TEST.replaceFirst("\\s+","才"));
  23.  
  24. // 把符合正则式"\\s+"的字符串,全部替换成"才"
  25. System.out.println(EXAMPLE_TEST.replaceAll("\\s+","才"));
  26. }
  27. }

输出结果:

  1. true
  2. 15
  3. This
  4. is
  5. my
  6. small
  7. example
  8. string
  9. which
  10. I'm
  11. going
  12. to
  13. use
  14. for
  15. pattern
  16. matching
  17. .
  18. This才is my small example string which I'm going to use for pattern matching .
  19. ThisismysmallexamplestringwhichI'm才going才tousefor才pattern才matching才.

java. util. regex

import java.util.regex.Matcher 和 java.util.regex.Pattern,里面有很多方法可以用

  1. package regextest;
  2.  
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5.  
  6. public class RegexMatches
  7. {
  8.  
  9. public static void main(String[] args)
  10. {
  11. String line = "The price for iPhone is 5288,which is a little expensive.";
  12. // 提取字符串中的唯一的数字,圆括号是用来分组的, ^ 是“取反”的意思
  13. String regex = "(.*[^\\d])(\\d+)(.*)";
  14.  
  15. // 创建 Pattern 对象
  16. Pattern pattern = Pattern.compile(regex);
  17.  
  18. // 创建 matcher 对象
  19. Matcher mather = pattern.matcher(line);
  20.  
  21. if (mather.find())
  22. {
  23. System.out.println("Found value: " + mather.group(2));
  24. }
  25. else
  26. {
  27. System.out.println("NO MATCH");
  28. }
  29. }
  30.  
  31. }

输出结果:

  1. Found value: 5288

grok 更加强大的 regex

在 Matcher,Pattern 的基础上, import 了很多包;进行了升级,可以调用方法更多,更加强大。

  1. import com.google.code.regexp.Matcher;
  2. import com.google.code.regexp.Pattern;
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.File;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileReader;
  8. import java.io.IOException;
  9. import java.io.Reader;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.TreeMap;
  14. import org.apache.commons.lang3.StringUtils;

某网站对Grok的定义:
Java Grok is simple tool that allows you to easily parse logs and other files (single line). With Java Grok,you can turn unstructured log and event data into structured data (JSON).

Java Grok program is a great tool for parsing log data and program output. You can match any number of complex patterns on any number of inputs (processes and files) and have custom reactions.

一个简单的例子:从日志文件中读取数据,提取想要的信息:一是时间,二是来源IP

输入:

  1. Mon Nov 9 06:47:33 2015; UDP; eth1; 461 bytes; from 88.150.240.169:tag-pm to 123.40.222.170:sip
  2. Mon Nov 9 06:47:34 2015; UDP; eth1; 463 bytes; from 88.150.240.169:49208 to 123.40.222.170:sip
  3. Mon Nov 9 06:47:34 2015; UDP; eth1; 463 bytes; from 88.150.240.169:54159 to 123.40.222.170:sip
  4. Mon Nov 9 06:47:34 2015; UDP; eth1; 463 bytes; from 88.150.240.169:53640 to 123.40.222.170:sip
  5. Mon Nov 9 06:47:34 2015; UDP; eth1; 463 bytes; from 88.150.240.169:52483 t
  1. package com.yz.utils.grok.api;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8.  
  9. public class GrokTest
  10. {
  11.  
  12. public static void main(String[] args)
  13. {
  14. FileInputStream fiStream = null;
  15. InputStreamReader iStreamReader = null;
  16. BufferedReader bReader = null;
  17. //用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的,而InputStreamReader没有。
  18.  
  19. try
  20. {
  21. String line = "";
  22. // 从文件系统中的某个文件获取字节
  23. fiStream = new FileInputStream("C:\\dev1\\javagrok\\javagrok\\iptraf_eth1_15.06.11");
  24.  
  25. // InputStreamReader 是字节流通向字符流的桥梁
  26. iStreamReader = new InputStreamReader(fiStream);
  27.  
  28. // 从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象
  29. bReader = new BufferedReader(iStreamReader);
  30.  
  31. Grok grok = new Grok();
  32. // Grok 提供了很多现成的pattern,可以直接拿来用。用已有的pattern,来构成新的pattern。
  33. grok.addPatternFromFile("c:\\dev1\\cloudshield\\patterns\\patterns");
  34.  
  35. grok.addPattern("fromIP","%{IPV4}");
  36. // compile 一个 pattern,期间我被空格坑了一下
  37. grok.compile(".*%{MONTH}\\s+%{MONTHDAY}\\s+%{TIME}\\s+%{YEAR}.*%{fromIP}.* to 123.40.222.170:sip");
  38. Match match = null;
  39.  
  40. while((line = bReader.readLine()) != null) // 注意这里的括号,被坑了一次
  41. {
  42. match = grok.match(line);
  43. match.captures();
  44. if(!match.isNull())
  45. {
  46. System.out.print(match.toMap().get("YEAR").toString() + " ");
  47. System.out.print(match.toMap().get("MONTH").toString() + " ");
  48. System.out.print(match.toMap().get("MONTHDAY").toString() + " ");
  49. System.out.print(match.toMap().get("TIME").toString() + " ");
  50. System.out.print(match.toMap().get("fromIP").toString() + "\n");
  51. }
  52. else
  53. {
  54. System.out.println("NO MATCH");
  55. }
  56. }
  57.  
  58. }
  59. catch (FileNotFoundException fnfe)
  60. {
  61. System.out.println("file not found exception");
  62. fnfe.printStackTrace();
  63. }
  64. catch (IOException ioe)
  65. {
  66. System.out.println("input/output exception");
  67. ioe.printStackTrace();
  68. }
  69. catch (Exception e)
  70. {
  71. System.out.println("unknown exception");
  72. e.printStackTrace();
  73. }
  74. finally
  75. {
  76. try
  77. {
  78. bReader.close();
  79. iStreamReader.close();
  80. fiStream.close();
  81. }
  82. catch(IOException ioe)
  83. {
  84. System.out.println("input/output exception");
  85. ioe.printStackTrace();
  86. }
  87. }
  88. }
  89.  
  90. }

输出

  1. 2015 Nov 9 06:47:33 88.150.240.169
  2. 2015 Nov 9 06:47:34 88.150.240.169
  3. 2015 Nov 9 06:47:34 88.150.240.169
  4. 2015 Nov 9 06:47:34 88.150.240.169
  5. NO MATCH

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