javaandroidstringspecial-characters

How can I remove special character with number from a String in android Java?


I have a String like this: 1984 (as Word$55), 1984-1993 (as Something$74435), 1994-present (as Anything$9324879)

I want to remove the special character $ and the number afterwards so for the final result be 1984 (as Word), 1984-1993 (as Something), 1994-present (as Anything)

How can I do this?

I have tried to use split like this: String s = previousString.split("\\$")[0] + ")"; but it cut the last part of the String, so the result looks like this:

1984 (as Word), 1984-1993 (as Something)


Solution

  • You could use string.replaceAll which accepts a regex to remove a $ followed by one or more digits:

    String input = "1984 (as Word$55), 1984-1993 (as Something$74435), 1994-present (as Anything$9324879)";
    input = input.replaceAll("\\$\\d+", "");
    
    System.out.println(input);