“Go“ regular expression greedy and non-greedy mode-Alibaba Cloud

Turn from: http://www.cnblogs.com/xudong-bupt/p/3586889.html Regular expression greedy and non-greedy mode.

Before doing the program to see the regular expression of greed and non-greedy mode, today, when the use of the time to remember, and now here to summarize, in case of their future use to pay attention to.

1. What is the greedy and non-greedy matching of regular expressions

  such as: String str= "ABCAXC";

Patter p= "Ab*c";

greedy Matching: regular expressions tend to match the maximum length, which is called greedy matching. As above using pattern p to match string str, the result is matched to:abcaxc(ab*c).

  non-greedy match : just match to the result is good, fewer match characters. As above using pattern p to match string str, the result is matched to:ABC(AB*C).

2. How to differentiate between two modes in programming

  The default is greedy mode; Add a question mark directly after the quantifier? is the non-greedy mode.

Quantifier: {m,n}:m to n

*: Any number of

+: one to multiple

? : 0 or one

3. Program examples

Use snort's rule as part of a rule to match the text, matching the content part.

1 Import java.util.regex.Matcher; 
2 Import Java.util.regex.Pattern; 
3  4 public class Regulartest {5      6 public     static void Main (string[] arg) {7         String text= "(content:\" RCPT t o root\ ";p cre:\" word\ ";)"; 8         String rule1= "content:\". +\ "";    Greedy mode 9         String rule2= "content:\". +?\ "";    Non-greedy mode         System.out.println ("text:" +text),         System.out.println ("Greedy mode:" +rule1);         P1 =pattern.compile (rule1);         Matcher m1 = p1.matcher (text), while         (M1.find ()) {             System.out.println ("Match result:" +m1.group (0)),         }18         System.out.println ("non-greedy Mode:" +rule2);         Pattern p2 =pattern.compile (rule2)         Matcher m2 = p2.matcher (text), while         (M2.find ()) {             System.out.println ("Match result:" +m2.group (0));         }25     }26}

Execution Result:

4. Note

Not compiled successfully using Linux C? Non-greedy mode of the number.

A word on the Internet: the? only works for perl-based RegExp, not for POSIX ...

"Go" regular expression greedy and non-greedy mode

Related Articel:

Greedy and non -Greedy pattern in regular expressions(Overview)

Greedy and non-Greedy patterns of regular expressions

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值