使用 groovy 正则表达式将“%@”替换为“%n$s”

Replace '%@' with '%n$s' using groovy regex

我有一个像 some text %@ some text %@ some text 这样的字符串 其中 %@ 是 obj-c 格式。我需要将此字符串转换为 some text %1$s some text %2$s some text ,这是一个带有格式的 android 资源。

如何使用 groovy 正则表达式来完成?

你有一个字符串 some text %@ some text %@ some text.

您可以使用 stringtokenizer 分割该字符串:

例如:

String myString= "Hello world"

//we can divide my string using space as reference on this way.
StringTokenizer tokens = new StringTokenizer(myString, " ");
                        //here hello
                        String SplitFirst = tokens.nextToken();
                        //here world
                        String SplitSecond = tokens.nextToken();

第二个例子:

String myString= "Hello:world:everybody"

//we can divide my string using `:` as reference on this way.
StringTokenizer tokens = new StringTokenizer(myString, ":");
                        //here hello
                        String SplitFirst = tokens.nextToken();
                        //here world
                        String SplitSecond = tokens.nextToken();
                        //here everybody
                        String SplitThird = tokens.nextToken();

那么关于你的问题,你可以做同样的过程来做到这一点,但作为参考 %@

当您有不同的字符串时,您可以使用 replace 来更改 %@:

例如

String newString = string.replace("%@", "%1$s");

稍后您可以连接新字符串:

再次,例如

String NewConcatenateString= SplitFirst + SplitSecond + SplitThird......

你可以这样做:

def s = 'some text %@ some text %@ some text'

def newS = 1.with { idx -> s.replaceAll(/%@/, { v -> "%${idx++}$s" }) }

给出输出:

'some text %1$s some text %2$s some text'