Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy String replacement

I have string in following format

some other string @[Foo Foo](contact:2) some other string @[Bar Bar](contact:1) still some other string

now I want this string into

some other string <a href="someurl/2">Foo Foo</a> some other string <a href="someurl/1">Bar Bar</a> still some other string

so basically need to replace the @[Some name](contact:id)to url using groovy &using reg ex what is the efficient way to do it

like image 741
user602865 Avatar asked Feb 04 '12 15:02

user602865


2 Answers

You can use the Groovy replaceAll String method with a grouping regular expression:

"some other string @[Foo Foo](contact:2) some other string @[Bar Bar](contact:1) still some other string"
.replaceAll(/@\[([^]]*)]\(contact:(\d+)\)/){ all, text, contact ->
    "<a href=\"someurl/${contact}\">${text}</a>"
}

/@\[([^]]*)]\(contact:(\d+)\)/ =~ @[Foo Foo](contact:2)
/ begins a regular expression pattern
@ matches @
\[ matches [
( begins the text group
[^]]* matches Foo Foo
) ends the text group
] matches ]
\(contact: matches (contact:
( begins the contact group
\d+ matches 2
) ends the contact group
\) matches )
/ ends the regular expression pattern

like image 72
James Allman Avatar answered Oct 30 '22 00:10

James Allman


You don't mention the programming language, but generically assuming the language does s/// type regexp syntax somehow:

s/@\[([^\]]+)\]\([^:]+:([0-9]+)\)/<a href="someurl\/$2">$1<\/a>/g

That'll work in most regexp languages. For example, it works in perl (though I'm escaping the special @ character which means something in perl:

#echo "some other string @[Foo Foo](contact:2) some other string @[Bar Bar](contact:1) still some other string" | perl -p -e 's/\@\[([^\]]+)\]\([^:]+:([0-9]+)\)/<a href="someurl\/$2">$1<\/a>/g' 
some other string <a href="someurl/2">Foo Foo</a> some other string <a href="someurl/1">Bar Bar</a> still some other string
like image 44
Wes Hardaker Avatar answered Oct 29 '22 23:10

Wes Hardaker