Replace all verbs in Printf format to %v

158 views
Skip to first unread message

Archos

unread,
Dec 31, 2011, 5:49:18 AM12/31/11
to golang-nuts
I've a string with the verb's format for Printf, and I would want to
convert to %s (because I've each into string)

===
package main

import (
"fmt"
"regexp"
)

var value = "\"(%d, %d) = %d\\n\""

func main() {
// The idea is replace [bcdefgopqstvxEGTUX] by 'v' after of be
matched
reVerb := regexp.MustCompile(`[^\\]%[+\-# 0]?([bcdefgopqstvxEGTUX])`)

r := reVerb.ReplaceAllString(value, "v")
fmt.Println(value)
fmt.Println(r)
}
===
But the result isn't what I was expecting

"v,v) =v\n"

Archos

unread,
Dec 31, 2011, 5:59:00 AM12/31/11
to golang-nuts
Sorry! That doesn't solve my problem.

I've to split the string in each verb

Jan Mercl

unread,
Dec 31, 2011, 6:06:29 AM12/31/11
to golan...@googlegroups.com
This works in the limited case where %% is not present. Note: \% is not a valid escape seq.

package main

import (
        "fmt"
        "regexp"
)

var value = "\"(%d, %d) = %d\\n\""

func main() {
        reVerb := regexp.MustCompile(`%[+\-# 0]?([bcdefgopqstvxEGTUX])`)
        r := reVerb.ReplaceAllString(value, "%v")
        fmt.Println(value)
        fmt.Println(r)
}

12:05 myname@tux64:~/tmp/go$ make && ./tmp 
6g   -o _go_.6 tmp.go 
6l  -o tmp _go_.6
"(%d, %d) = %d\n"
"(%v, %v) = %v\n"
12:05 myname@tux64:~/tmp/go$

Archos

unread,
Dec 31, 2011, 6:10:19 AM12/31/11
to golang-nuts


On Dec 31, 11:06 am, Jan Mercl <jan.me...@nic.cz> wrote:
> This works in the limited case where %% is not present. Note: \% is not a
> valid escape seq.
That's my failure. I was using [^\\] to skip verbs like `\%s` but I
see that it isn't valid.

Sol Toure

unread,
Dec 31, 2011, 9:18:28 AM12/31/11
to golang-nuts
 It is valid. But since regexp does not support expressions such as $1 or \1 you need to use "regexp.ReplaceAllStringFunc" instead.

Your replacement become:
r := reVerb.ReplaceAllStringFunc(value, func(s string)string{return string(s[:len(s)-1])+"v"})

Kyle Lemons

unread,
Jan 1, 2012, 6:25:07 PM1/1/12
to Archos, golang-nuts
You need to do more than just s/%./%v/ to get a proper translation.  Things like %q and %.5f have very specific meanings that you will break.  The quoted-string verb, in particular, is important and not maintaining its semantics could introduce security issues.
Reply all
Reply to author
Forward
0 new messages