Cristian Santiago
Cristian Santiago

Reputation: 3

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

Upvotes: 0

Views: 349

Answers (4)

Hatem
Hatem

Reputation: 31

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

[A-Z] 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", "");

Upvotes: 1

Asew
Asew

Reputation: 374

Try this :

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

Upvotes: 0

Sanjay
Sanjay

Reputation: 1108

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);

Upvotes: 0

Martin Schneider
Martin Schneider

Reputation: 3268

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"

Upvotes: 1

Related Questions