Do regular expression replace in submatch

1,282 views
Skip to first unread message

Tong Sun

unread,
Jan 15, 2016, 3:18:34 PM1/15/16
to golang-nuts
The Go by Example: Regular Expressions at https://gobyexample.com/regular-expressions only shows how to do normal regular expression find and replace, but I want to do regular expression replace in submatch. I.e., locate a string range with regular expression find, and do regular expression replace within that range. 

Is that possible? 

I found this, "no way to replace submatches with a function #5690"

but I don't need a function if I can make it works. 

Thanks


Shawn Milochik

unread,
Jan 15, 2016, 3:33:41 PM1/15/16
to golang-nuts
It sounds like you can use one of the Find* methods to locate the substring, then concatenate the string up to that point, the result of one of the Replace* methods for the substring, then the remainder of the string. So, two separate regexp patterns, but it should work.

Can you give sample input and output? Maybe someone will have a better suggestion based on the actual need.

Tong Sun

unread,
Jan 15, 2016, 3:39:30 PM1/15/16
to Sh...@milochik.com, golang-nuts
Thanks. The input in that issues/5690 is a good one

Let's say you have strings like

    input := `bla b:foo="hop" blabla b:bar="hu?"`

and you want to replace the part between quotes in b:foo="hop" and
b:bar="hu?", replacing "b:" with "new:", and replacing "hop" with "hope". 

Thanks



On Fri, Jan 15, 2016 at 3:32 PM, Shawn Milochik <shawn...@gmail.com> wrote:
It sounds like you can use one of the Find* methods to locate the substring, then concatenate the string up to that point, the result of one of the Replace* methods for the substring, then the remainder of the string. So, two separate regexp patterns, but it should work.

Can you give sample input and output? Maybe someone will have a better suggestion based on the actual need.

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/dBbQoxdPW5w/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Shawn Milochik

unread,
Jan 15, 2016, 5:08:42 PM1/15/16
to golang-nuts
Does this solve your use-case?



Tong Sun

unread,
Jan 15, 2016, 9:41:58 PM1/15/16
to golang-nuts

On Fri, Jan 15, 2016 at 5:08 PM, Shawn Milochik <sh...@milochik.com> wrote:

Does this solve your use-case?


Oh, thanks a lot Shawn! 

Actually what I am trying to do is to html-encode a sub-set-part of an XML string. I think your first description is a viable option. 

thanks again.
Reply all
Reply to author
Forward
0 new messages