Writing regular Expressions in groovy

Source: Internet
Author: User
Tags assert regular expression

Writing regular Expressions (regexes) in groovy is a pleasure compared to Java. In Java, regexes programming requires not only the processing of pattern and Matcher objects, but also the writing of tedious boilerplate code (boilerplate coding). Groovy does a simple encapsulation of these two Java objects, adds some additional practical methods, and gives a simplified new syntax and 3 new operators.

In groovy, you can use Slashy (slash) syntax "/.. /"defines a string. This avoids the use of too many backslashes in Java regular expressions. For example:

ASSERT (/hello world/in String)
ASSERT (/hi \there/= = ' Hi \\there ')

The 1th new regular expression operator in groovy is the pattern operator (~), which causes the string to be compiled into an instance of patterns. For example:

p = ~/\b[a-za-z]\b/

You can also use Java implementations, such as:

Import java.util.regex.*
Pattern p = pattern.compile ("\\b[a-za-z]\\b");

The common regular expression patterns and meanings are listed in Table 3.1. A complete regular expression manifest can refer to the Pattern API documentation, http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html.

Table 3.1 Common Regular expression patterns

Pattern meaning

A?

Match as many as 1 times a, or you can not match

A *

expression as much as possible to match a, at least not match

A +

Match A as much as possible and match at least 1 times

A|b

Match A or B

(AB)

Group

.

Match any one character

[ABC]

Match A,b or C

[^ABC]

Match any one character except A,b or C

[A-z]

Match any letter between A and Z

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.