Groovy replacement part

I have a line in the following format

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

now i want this line in

 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 you need to replace @[Some name](contact:id) with url using groovy & using reg ex, which is an efficient way to do this

+7
source share
2 answers

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

 "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)
/ starts the regex pattern
@ matches @
\[ matches [
( group text begins
[^]]* matches Foo Foo
) completes the group text
] matches ]
\(contact: matches (contact:
( contact group starts
\d+ matches 2
) completes the contact group
\) matches )
/ completes the regex pattern

+10
source

You did not mention the programming language, but in the general case, assuming that the language s /// is of type regexp syntax in some way:

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

This will work in most regular expression languages. For example, it works in perl (although I avoid the special @ symbol, 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 
+2
source

All Articles