简体   繁体   English

替换 Java 字符串中出现的部分但不是所有字符

[英]Replacing some but not all occurrences of a char in Java String

I am learning Java, and in a task I have to replace some but not all occurrences of a '-' to a '(' and same for '*' a ')', only if the inside of the - is an id as as follows:我正在学习Java,并且在一项任务中,我必须将一些但不是所有出现的“-”替换为“(”,并且对于“*”和“)”也是如此,前提是 - 的内部是一个 id 为如下:

String input = "-id1234* -id1235* -id1236* Do not replace these -signs*";
String output = "(id1234) (id1235) (id1236) Do not replace these -signs*";

I have tried iterating through a loop, and replacing the first occurrence once the for loop goes to a position with i , but that doesn't seem to work:我尝试遍历一个循环,并在 for 循环到达i位置后替换第一次出现,但这似乎不起作用:

    static String clean(String input) {
        
        String tmp = input;
        
        for (int i = 0; i < input.length(); i++) {
            
            if (input.charAt(i) == 'i') {
            tmp = input.replaceFirst("-", "("); 
            } else if(Character.isDigit(i)){
                 tmp = input.replaceFirst("*", ")");
            }
        }
        
        return tmp; 
    }

You didn't say how your method doesn't seem to work, but it looks like you are replacing "*" with ")" for every digit you find: the 1, the 2, the 3, the 4, then the 1, 2, 3, 5, so that many more end parentheses replace asterisks than you expect.你没有说你的方法似乎不起作用,但看起来你正在用“)”替换你找到的每个数字:1、2、3、4,然后是 1 , 2, 3, 5,所以用更多的括号代替星号。

This assumes that "id" followed by numbers is always what you want to match in between the "-" and the "*".这假定后跟数字的“id”始终是您想要在“-”和“*”之间匹配的内容。 Use a regular expression to match and replace with the replaceAll method :使用正则表达式匹配并替换为replaceAll方法

return input.replaceAll("-(id\\d+)\\*", "($1)");

Match a - .匹配一个- Form a capturing group in your regular expression with parentheses.用括号在正则表达式中形成一个捕获组。 Match id .匹配id Match one or more digits consecutively.连续匹配一个或多个数字。 After the capturing group, match a * .在捕获组之后,匹配一个* The backslashes are for 1) escaping a literal backslash to form the character class \d - digits, and 2) escaping a literal backslash to regex-escape the asterisk.反斜杠用于 1) 转义文字反斜杠以形成字符类 \d - 数字,以及 2) 转义文字反斜杠以正则表达式转义星号。

The $1 inside the replacement expression means the first capturing group.替换表达式中的$1表示第一个捕获组。

Output:输出:

(id1234) (id1235) (id1236) Do not replace these -signs*

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

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