简体   繁体   中英

Replacing certain combination of characters

I'm trying to remove the first bad characters (CAP letter + dot + Space) of this.

A. Shipping Length of Unit
C. OVERALL HEIGHT
Overall Weigth
X. Max Cutting Height

I tried something like that, but it doesn't work:

string.replaceAll("[A-Z]+". ", "");

The result should look like this:

Shipping Length of Unit
OVERALL HEIGHT
Overall Weigth
Max Cutting Height

This should work:

string.replaceAll("^[A-Z]\\. ", "")

Examples

"A. Shipping Length of Unit".replaceAll("^[A-Z]\\. ", "")
// => "Shipping Length of Unit"
"Overall Weigth".replaceAll("^[A-Z]\\. ", "")
// => "Overall Weigth"
input.replaceAll("[A-Z]\\.\\s", "");

[AZ] matches an upper case character from A to Z
\\. matches the dot character
\\s matches any white space character

However, this will replace every character sequence that matches the pattern. For matching a sequence at the beginning you should use

input.replaceAll("^[A-Z]\\.\\s", "");

Try this :

myString.replaceAll("([A-Z]\\.\\s)","")
  • [AZ] : match a single character in the range between A and Z.
  • \\. : match the dot character.
  • \\s : match the space character.

Without looking your code it is hard to tell the problem. but from my experience this is the common problem which generally we make in our initial days:

String string = "A. Test String";
string.replaceAll("^[A-Z]\\. ", "");
System.out.println(string);

String is an immutable class in Java. what it means once you have create a object it can not be changed. so here when we do replaceAll in existing String it simply create a new String Object. that you need to assign to a new variable or overwrite existing value something like below :

String string = "A. Test String";
string  = string.replaceAll("^[A-Z]\\. ", "");
System.out.println(string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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