1

I have a string like 23.Piano+trompet, and i wanted to remove the 23. part from the string using this function:

private String removeSignsFromName(String name) {
    name = name.replaceAll(" ", "");
    name = name.replaceAll(".", "");

    return name.replaceAll("\\^([0-9]+)", "");
}

But it doesn't do it. Also, there is no error in runtime.

2
  • 2
    You escape the ^, so it searches for a literal ^, which is not present. Commented Jan 6, 2017 at 11:46
  • 4
    . matches any character and replaceAll() replaces all the characters. Escape the dot "\\." Commented Jan 6, 2017 at 11:47

6 Answers 6

3

The following replaces all whitespace characters (\\s), dots (\\.), and digits (\\d) with "":

name.replaceAll("^[\\s\\.\\d]+", "");

what if I want to replace the + with _?

name.replaceAll("^[\\s\\.\\d]+", "").replaceAll("\\+", "_");
Sign up to request clarification or add additional context in comments.

Comments

2

You don't need to escape the ^, you can use \\d+ to match multiple digits, and \\. for a literal dot and you don't need multiple calls to replaceAll. For example,

private static String removeSignsFromName(String name) {
    return name.replaceAll("^\\d+\\.", "");
}

Which I tested like

public static void main(String[] args) {
    System.out.println(removeSignsFromName("23.Piano+trompet"));
}

And got

Piano+trompet

1 Comment

he needs the ^, if he want to make sure the replacement can only occur on the beginning of string. however he should not escape the ^ Your pattern will replace all number + dots in the text, don't know if it is desired. Also, what for the grouping, it makes no sense, does it?
1

Two problems:

  1. The . in the second replaceAll should be escaped:

    name=name.replaceAll("\\.", "");
    
  2. The ^ in the third one should NOT be escaped:

    return name.replaceAll("^([0-9]+)", "");
    

Oh! and the parentheses are useless since you don't use the captured string.

Comments

1

How about this:

public static String removeNumOfStr(String str) {
    if (str == null) {
        return null;
    }
    char[] ch = str.toCharArray();
    int length = ch.length;
    StringBuilder sb = new StringBuilder();
    int i = 0;
    while (i < length) {
        if (Character.isDigit(ch[i])) {
            i++;
        } else {
            sb.append(ch[i]);
            i++;
        }
    }
    return sb.toString();
}

Comments

0
return name.replaceFirst("^\\d+\\.", "");

Comments

-1
public static void removenum(String str){

    char[] arr=str.toCharArray();
    String s="";

    for(char ch:arr){

        if(!(ch>47 & ch<57)){

            s=s+ch;
        }
            }
    System.out.println(s);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.