Skip to content

golang regex replace problem #29936

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
kzhui125 opened this issue Jan 25, 2019 · 2 comments
Closed

golang regex replace problem #29936

kzhui125 opened this issue Jan 25, 2019 · 2 comments

Comments

@kzhui125
Copy link

https://play.golang.org/p/G7VF0QgUxGi

package main

import (
    "regexp"
    "fmt"
)

func main() {
    // var re = regexp.MustCompile(`(=\s*)D\s+('.*?')`)
    var re = regexp.MustCompile(`(?m)(=\s*)D\s+('.*?')`)
    var str = `a = D '123' b`
    var substitution = "$1xx$2"
    
    fmt.Println(re.ReplaceAllString(str, substitution))
}

expected: a = xx'123' b
actual: a '123' b

@ianlancetaylor
Copy link
Contributor

ReplaceAllString treats the substitution string as though passed to Expand, and in Expand a $ may be followed by a name, and a name is a non-empty sequence of letters, digits, and underscores. So in your substitution string you are substituting $1xx (which is not defined) and then $2. Write instead ${1}xx${2}.

@kzhui125
Copy link
Author

@iamoryanmoshe Thanks very much.

I saw the comment "so for instance $1", so I used $1.

123

And in my experience $1 is more general than ${1}
(php support ${1}, not support $1).

c#

string s1= Regex.Replace("123456", @"(12)34(56)", @"$1xxx$2"); // 12xxx56
string s2 = Regex.Replace("123456", @"(12)34(56)", @"${1}xxx${2}"); // 12xxx56

js:

'123456'.replace(/(12)34(56)/g,'$1xxx$2') // "12xxx56"
'123456'.replace(/(12)34(56)/g,'${1}xxx${2}') // "${1}xxx${2}"

python:

import re 

s = '123456'
re_test = re.compile(r'(12)34(56)')
print(re_test.sub(r'\1xxx\2',s)) # 12xxx56
print(re_test.sub(r'\{1}xxx\{2}',s)) # \{1}xxx\{2}

java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexMatches {

    public static void main(String[] args) {
    
        Pattern p = Pattern.compile("(12)34(56)");
        // get a matcher object
        Matcher m = p.matcher("123456"); 
        System.out.println(m.replaceAll("$1xxx$2")); // 12xxx56
        // System.out.println(m.replaceAll("${1}xxx${2}")); // invalid
   }
}

@golang golang locked and limited conversation to collaborators Jan 25, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants