tommycat
tommycat

Reputation: 29

using groovy RegEx to grabbing values of attribute: code from grails message tag

I have parsed a gsp file into String and then i want to retrieve all values of the attribute "code" from grails message tag (including ${message...) as following:

deployment.order.label  
no.using.xx.label  
default.button.start.label

I have tried a lot by matching this with code="value" | code='value' | code: 'value' | code: "value" in RegEx, but still not working. can some RegEx expert help me out? thanks.

this is a start 
<g:message code="deployment.order.label" default="Definition order" />
dddfg fgfr
${message(code: "no.using.xx.label", default: 'Start')}"
this is a usf
<g:actionSubmit class="start" id="start" 
value="${message(code: 'default.button.start.label', default: 'Start')}" action="start"/>
kkkkk

Upvotes: 0

Views: 219

Answers (2)

Mike W
Mike W

Reputation: 3932

Only grabbing the value of the code:

Full expression: /(?<=code[=:]\s?["'])([\w.]+)(?=["'])/

(?<=code[=:]\s?["']) using a positive lookbehind, assert the presence of this expression but don't include in results

([\w.]+) get the text

(?=["'])/) using a positive lookahead, again assert presence of this expression but exclude from results

def str = '''this is a start <g:message code="deployment.order.label" default="Definition order" />
dddfg fgfr
${message(code: "no.using.xx.label", default: 'Start')}"
this is a usf
<g:actionSubmit class="start" id="start"
value="${message(code: 'default.button.start.label', default: 'Start')}" action="start"/>
kkkkk'''

def group = ( str =~ /(?<=code[=:]\s?["'])([\w.]+)(?=["'])/)

assert 3 == group.count
assert 'deployment.order.label' == group[0][0]
assert 'no.using.xx.label' == group[1][0]
assert 'default.button.start.label' == group[2][0]

Upvotes: 1

volkinc
volkinc

Reputation: 2128

The regex will be like this:

/(?:code(?:[=:])\s*?\\?(?:["']))([\w+\.]+)*(?:["'])/ig
  1. (?:code(?:[=:])\s*?\?(?:["'])) - match word code with all variation of quotes.
  2. ([\w+\.]+)* - match your value

  3. (?:["']) - match closed quotes

Hope this will help.

The test script in perl will be like this:

#!/usr/bin/perl
use Data::Dumper;

$subject = "this is a start 
<g:message code=\"deployment.order.label\" default=\"Definition order\" />
dddfg fgfr
{message(code: \"no.using.xx.label\", default: \'Start\')}\"
this is a usf
<g:actionSubmit class=\"start\" id=\"start\" 
value=\"{message(code: \'default.button.start.label\', default: \'Start\')}\" action=\"start\"\/>
kkkkk";

my @matches;
push @matches, [$1, $2] while $subject =~ /(?:code(?:[=:])\s*?\\?(?:["']))([\w+\.]+)*(?:["'])/ig;

print Dumper(\@matches);

Upvotes: 1

Related Questions