Skip to content

Instantly share code, notes, and snippets.

@yongchun
Created February 11, 2014 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yongchun/8936244 to your computer and use it in GitHub Desktop.
Save yongchun/8936244 to your computer and use it in GitHub Desktop.
java正则简单用列
package com.simple.example;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* java正则工作中的使用
* ==========================================
* ^A匹配以A开头
* $A匹配以A结尾
* \s?匹配0个或多个空格
* \S+表示至少一个字符
* \S{0,6}表示0到6个字符
* [0-9]*匹配0到9的数字(多个)
* ()将括号里面的内容作为一个独立的单元,理解为一组,用于获取对应的字符串使用
* ============================================
* java正则入门可以参考: http://su1216.iteye.com/blog/1570964
*
* @author xiangnong
* @author yongchun.chengyc@gmail
*/
public class RegTest {
private static final String OCTCHECK_2 = "^-A\\s?INPUT\\s?-s\\s?(\\S+)\\s?-p\\s?(\\S{0,6})\\s?-m\\s?(\\S{0,6})\\s?--dport\\s?([0-9]*)\\s?-j\\s?ACCEPT$";
private static final Pattern otcReg2 = Pattern.compile(OCTCHECK_2);
public static void main(String args[]) {
Matcher matcher = otcReg2.matcher("-A INPUT -s 210.51.31.11 -p tcp -m tcp --dport 38422 -j ACCEPT");
if (matcher.matches()) {
System.out.println(matcher.group()); // 和matcher.group(0)等价
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
//输出结果为:
/**
* -A INPUT -s 210.51.31.11 -p tcp -m tcp --dport 38422 -j ACCEPT
* 210.51.31.11
* tcp
* tcp
* */
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment