tavalendo
tavalendo

Reputation: 877

Remove last digit in a string in Java only if it is just one digit present

I would like to remove last digit in a Java string, only if it is just one digit present.

E.g.

String text = "I am the9 number1"; // should be "I am the number"

Cases where it should do nothing:

String = "I913 am the55 number11"; // Should remain the same.

I tried this without success:

String text = "I am the1 number1";
text = text.replaceAll("^[0-9]$", "");

Didnt work. Any help?

Upvotes: 2

Views: 128

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

To replace the last digit in a string you may use

text = text.replaceAll("\\B(?<!\\d)\\d\\b", "");

See the regex demo.

Details

  • \B - a letter or _ must appear immediately to the left of the current position
  • (?<!\d) - a negative lookbehind that fails the match if there is a digit immediately to the left of the current location
  • \d - a digit
  • \b - a word boundary.

Java demo:

String rx = "\\B(?<!\\d)\\d\\b";
System.out.println("I am the number1".replaceAll(rx, ""));
// => I am the number
System.out.println("I am the number11".replaceAll(rx, "")); 
// => I am the number11
System.out.println("I am 4the number1 @#@%$grtuy".replaceAll(rx, "")); 
// => I am 4the number @#@%$grtuy
System.out.println("I am number1 1 and you number2 2".replaceAll(rx, ""));
// => I am number 1 and you number 2

Upvotes: 1

Javad Rezaei
Javad Rezaei

Reputation: 1110

You can use

(?<=[A-Za-z])\d(?!\d)

Regex Demo

Details

(?<=[A-Za-z]): it indicates word character before digit as positive lookbehind

\d: indicates number

(?!\d): there has to be no other number after matched number (negative lookahead)

Sample Code

text = text.replaceAll("(?<=[A-Za-z])\d(?!\d)", "");

Upvotes: 1

Related Questions