I have String
from which I need to extract a keyword.
Something like: “I have 100 friends and 1 evil”.
I need to extract “100” from that String
using only replaceAll
function and appropriate regex
.
I tried to do it in that way:
String input = "I have 100 friends and 1 evil"; String result = input.replaceAll("[^\d{3}]", "")
But it doesn’t work. Any help would be appreciated.
Advertisement
Answer
You can consider any of the solutions below:
String result = input.replaceFirst(".*?(\d{3}).*", "$1"); String result = input.replaceFirst(".*?(?<!\d)(\d{3})(?!\d).*", "$1"); String result = input.replaceFirst(".*?\b(\d{3})\b.*", "$1"); String result = input.replaceFirst(".*?(?<!\S)(\d{3})(?!\S).*", "$1");
See the regex demo. NOTE you may use replaceAll
here, too, but it makes little sense as the replacement must occur only once in this case.
Here,
.*?
– matches any zero or more chars other than line break chars, as few as possible(d{3})
– captures into Group 1 any three digits.*
– matches any zero or more chars other than line break chars, as many as possible.
The (?<!d)
/ (?!d)
lookarounds are digit boundaries, there is no match if the sequence is four or more digits. b
are word boundaries, there will be no match of the three digits are glued to a letter, digit or underscore. (?<!S)
/ (?!S)
lookarounds are whitespace boundaries, there must be a space or start of string before the match and either a space or end of string after.
The replacement is $1
, the value of Group 1.
See the Java demo:
String input = "I have 100 friends and 1 evil"; System.out.println(input.replaceFirst(".*?(\d{3}).*", "$1")); System.out.println(input.replaceFirst(".*?(?<!\d)(\d{3})(?!\d).*", "$1")); System.out.println(input.replaceFirst(".*?\b(\d{3})\b.*", "$1")); System.out.println(input.replaceFirst(".*?(?<!\S)(\d{3})(?!\S).*", "$1"));
All output 100
.