Jumbala
Jumbala

Reputation: 4944

Regex to remove last word in String + additional characters

I am getting a String from a server and I have to use a regular expression to parse it.

I know how I would do it using String functions (String.split and the likes), but not with regexes, which is in the homework requirements.

The Strings look like this:

12345 <RECTANGLE> 100 200 300 400 </RECTANGLE>

I have to use a regex to make that String become:

12345 RECTANGLE 100 200 300 400

So basically, I have to remove all the following characters: "<", ">" and "/". I also have to remove the last word, so I guess I don't even have to check for "/" since removing the last word would probably remove the slash as well.

Right now I have:

shapeString.replaceAll("[</>]", "");

And it removes the characters I don't need, but I don't know how to remove the last word.

Upvotes: 3

Views: 8474

Answers (2)

Prasanth
Prasanth

Reputation: 5258

You can use replaceAll or alternatively, this:

shapeString = shapeString.substring(0, shapeString.lastIndexOf(' '));

for removing the last word.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

You can add

str.replaceAll(" [^ ]+$", "")

to remove the last word and the space preceding it.

Here is a link to ideone with a running example.

Upvotes: 6

Related Questions