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:
String input = "-id1234* -id1235* -id1236* Do not replace these -signs*";
String output = "(id1234) (id1235) (id1236) Do not replace these -signs*";
Run Code Online (Sandbox Code Playgroud)
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:
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;
}
Run Code Online (Sandbox Code Playgroud)
您没有说您的方法似乎不起作用,但看起来您正在将找到的每个数字的“*”替换为“)”:1、2、3、4,然后是 1 , 2, 3, 5,因此替换星号的末尾括号比您预期的要多。
这假设“id”后跟数字始终是您想要在“-”和“*”之间匹配的内容。使用正则表达式来匹配并替换为replaceAll方法:
return input.replaceAll("-(id\\d+)\\*", "($1)");
Run Code Online (Sandbox Code Playgroud)
匹配一个-. 用括号在正则表达式中形成一个捕获组。匹配id。连续匹配一位或多位数字。在捕获组之后,匹配*. 反斜杠用于 1) 转义文字反斜杠以形成字符类 \d - 数字,以及 2) 转义文字反斜杠以正则表达式转义星号。
$1替换表达式内部表示第一个捕获组。
输出:
(id1234) (id1235) (id1236) Do not replace these -signs*
Run Code Online (Sandbox Code Playgroud)