Bogdan
Bogdan

Reputation: 673

How can I remove the last character in a String that has another regex computation in Java?

I want to remove the following character from a String: <,>,t,d,/ and also to remove the last character after the first removal. And I want to do this on a single statement.

Regex for removing <,>,t,d,/:

 String codCIM =  element.toString().replaceAll("[<>,t,d,//]", ""); -WORKS FINE

Regex for removing <,>,t,d,/ AND the last character:

String codCIM =  element.toString().replaceAll("[<>,t,d,//].$", ""); -DONT WORK

Ex: "dtt>W43451005/dttt>" should be W4345100.
But I can only achieve: W43451005

Upvotes: 0

Views: 283

Answers (2)

Nowhere Man
Nowhere Man

Reputation: 19555

First, the expected output shows that a sequence consisting of d, t, <, >, / should be removed, and then the character before this match at the end of the string has to be removed.

This can be achieved with the following regexp:

System.out.println("dtt>W43451005/dttt>".replaceAll("([<>td/]|.[<>td/]*$)", ""));

Output

W4345100

Upvotes: 1

akuiper
akuiper

Reputation: 214967

Try use this regex: [<>td/]|.(?=[<>td/]*$)

regex 101


  • [<>td/] matches the target characters;
  • .(?=[<>td/]*$) matches the character before the ending target character sequence, which is basically the last character after removing all target characters;

Upvotes: 2

Related Questions