Saturday, March 10, 2012

Groovy: Regular Expressions and Multiple Lines

Regular expressions are sometimes used on text that spans multiple lines, which Groovy has support for. I had to search for how to enable multi-line searching, so I thought it would be good to post here.

To allow the expression to span multiple lines we can add (?ms) to the beginning of the expression.

Take the following example, where want to grab the entire book element from a single-line XML document:

    def xml = "<library><book><title>Effective Java</title><author>Bloch</author></book></library>"
def matcher = xml =~ /<book>.*<\/book>/
matcher.size() > 0 ? matcher[0] : "NOTHING"

This gives us an entire book:

    <book><title>Effective Java<title><author>Bloch<author><book>

If the XML was to span multiple lines however, we end up with NOTHING:

    def xml = """<library>
<book>
<title>Effective Java</title>
<author>Bloch</author>
</book>
</library>"""
def matcher = xml =~ /<book>.*<\/book>/
matcher.size() > 0 ? matcher[0] : "NOTHING"

Now if we add the (?ms), we will still get an entire book entry:

    def xml = """<library>
<book>
<title>Effective Java</title>
<author>Bloch</author>
</book>
</library>"""
def matcher = xml =~ /(?ms)<book>.*<\/book>/
matcher.size() > 0 ? matcher[0] : "NOTHING"

The above results in:

  <book>
<title>Effective Java<title>
<author>Bloch<author>
<book>

If you have any other tips or another way to accomplish the same thing, please feel free to leave a comment.

6 comments:

  1. ) Ecorptrainings.com provides GROOVY in hyderabad with best faculties on real time projects. We give the best online trainingamong the GROOVY in Hyderabad. Classroom Training in Hyderabad India

    ReplyDelete
  2. THANK YOU SO MUCH
    EXACTLY WHAT I WAS LOOKING FOR

    ReplyDelete
  3. Thanks for providing the best information it's very useful sap basis learners.

    SAP BASIS Course in Hyderabad
    Online SAP BASIS Training in USA

    ReplyDelete
  4. Yes ,

    This is interesting blog and valuable blog.thanks for sharing such a important blog.
    oracle fusion procurement online training

    ReplyDelete
  5. I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor
    lead live training in Oracle Fusion Financials online Training , World Class Virtual Instructor led training on Oracle fusion Financials Training. We have industry expert trainer. We provide Training Material and Software Support. calfre has successfully conducted 100000+ trainings in India, USA, UK, Australlia,
    Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.

    ReplyDelete
  6. perfect explanation about java programming .its very useful.thanks for your valuable information.best java institute in chennai | best java training in velachery

    ReplyDelete