'Regex for replacing Row numbers (1. & 2.) only in string
In one of my scenario , I wanted to replace specific strings mentioned below.
String S1 = "1.This is example of regex and call the mobile 400-199-1234.This statement is valid.2.This is second example of regex.10.This is tenth statement";
In the above string I wanted to replace 1., 2., 10. (only) with null value.
The String should like this
String S1 = "This is example of regex and call the mobile 400-199-1234.This statement is valid. This is second example of regex.This is tenth statement";
I have tried using the below regex - "[0-9]\\."
My Code looks like: S1=S1.replaceAll("[0-9]\\.","")
It replaces all values including the mobile number and the string looks like this:
String S1 = "This is example of regex and call the mobile 400-199-123This statement is valid. This is second example of regex.This is tenth statement";
Can someone help with regex?
Solution 1:[1]
If you are sure there should be no hyphen before the number to be removed, you can use a lookbehind with a word boundary on the left:
S1 = S1.replaceAll("\\b(?<!-)\\d+\\.", "");
See the regex demo. The \b(?<!-) part makes sure there is no word and - char before the removed number.
If there can be valid numbers with dots after that are preceded with hyphens, add a \d pattern before -:
S1 = S1.replaceAll("\\b(?<!\\d-)\\d+\\.", "");
to make sure the number is not matched after a digit + - char.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wiktor Stribiżew |
