简体   繁体   English

正则表达式 - 捕获花括号之间的增量数字

[英]Regex - capturing incremental numbers between curly braces

I have a piece of code that tries to repeatedly match a pattern with an incremented index inside a loop: 我有一段代码试图在循环内重复匹配模式和递增的索引:

for(int count = 0; count < args.length; count++) {
        message.replaceFirst("^\\{" + count + "\\d}$", args[count]);
    }

What I want to be able to do is replace occurrences of {0}, {1} and so on in the message string with those in args. 我希望能够做的是在消息字符串中替换args中出现的{0},{1}等。 But try as I might, I simply cannot get the pattern to match. 但尽量尝试,我根本无法得到匹配的模式。 I am no regex expert, but I have tried a variety of regex combinations based on other questions here. 我不是正则表达式专家,但我已经尝试了基于其他问题的各种正则表达式组合。 I also tried using the replace method in StringUtils to no avail. 我也尝试在StringUtils中使用replace方法无济于事。 Can anyone offer any suggestions? 有人可以提供任何建议吗?

Do not use a regex at all. 根本不要使用正则表达式。 You know your search string beforehand and it is constant (ie you can build it from constant strings plus variable count ) and thus there is no need to incorporate regular expressions. 您事先知道您的搜索字符串并且它是常量(即您可以从常量字符串和变量count构建它),因此不需要合并正则表达式。

The ^ and $ characters are anchors. ^$字符是锚点。 They match the beginning and end of the string. 它们匹配字符串的开头和结尾。 That expression will only match if the entire String is nothing but {\\\\d} . 只有当整个String只是{\\\\d}该表达式才会匹配。 I don't think they need to be there at all. 我认为他们根本不需要在那里。

Also, Strings are immutable in java, the correct usage would be message = message.replaceAll(blah); 另外,字符串在java中是不可变的,正确的用法是message = message.replaceAll(blah);

Try this regex: 试试这个正则表达式:

String pattern = "^\\{\\d+\\}$";

Explanation: 说明:

  1. From the start of the string get a { 从字符串的开头得到一个{
  2. Then get as many digits as possible 然后获取尽可能多的数字
  3. Until a } is reached in the end of the string 直到在字符串的末尾到达}

Example: 例:

String s = "{12}";
String pattern = "^\\{\\d+\\}$";
String s2 = s.replaceFirst(pattern, "9");

System.out.println(s2);

Outputs: 输出:

9

This should be fairly easy to apply to your code. 这应该很容易应用于您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM