-2

I want to delete from a string all numbers, except if they are stuck to a letter.
Ex : F5 45, AD12 should become: F5 , AD12
So far I have done that, which is not much... :

line.replaceAll("[0-9]+", ""))

If you have any idea... thx

thomas
  • 1,201
  • 2
  • 15
  • 35
  • You could match one or more digits while asserting that on the left there is not a digit or a letter `(?<![\p{L}\d])\d+` https://regex101.com/r/zX4WGB/1 – The fourth bird Nov 16 '20 at 11:35

2 Answers2

0

\b is regexp-ese for 'word break'. You can look up the precise definition, but it'll probably do what you want here, because both spaces and 'start or end of string' all count as a word break, and the thing itself doesn't actually match characters (thus, it doesn't delete those spaces), it succeeds or fails based on whether there is a word-break character there.

Thus:

line.replaceAll("\\b[0-9]+\\b", "");

should get it done.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • The problem I see with this are numbers that end with a letter like 34D..you will not get these – micpog90 Nov 16 '20 at 11:40
  • @micpog90 that seems like what OP wants, no? 34D should not be turned into just D. Question says 'stuck to a letter', not 'prefixed by a letter'. – rzwitserloot Nov 16 '20 at 11:54
-1

If I understand your use case correctly, it should be something like this:

line.replaceAll("([^a-zA-Z]+)[0-9]+", "$1")

The first bit matches "anything except the letters a-z", the rest matches numbers. The second parameter retains the first character matched, so we don't remove any spaces or commas from your input.

Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26