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*";
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;
}
CodePudding user response:
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.
This assumes that "id" followed by numbers is always what you want to match in between the "-" and the "*". Use a regular expression to match and replace with the replaceAll
method:
return input.replaceAll("-(id\\d )\\*", "($1)");
Match a -
. Form a capturing group in your regular expression with parentheses. Match 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.
The $1
inside the replacement expression means the first capturing group.
Output:
(id1234) (id1235) (id1236) Do not replace these -signs*