Given String
// 1 2 3
String a = "letters.1223434.more_letters";
I’d like to recognize that numbers come in a 2nd position after the first dot
I then would like to use this knowledge to replace “2nd position of”
// 1 2 3
String b = "someWords.otherwords.morewords";
with “hello” to effectively make
// 1 2 3
String b = "someWords.hello.morewords";
Substitution would have to be done based on the original position of matched element in String a
How can this be done using regex please?
For finding those numbers you can use group mechanism (round brackets in regular expresions):
BUT if your goal is just replacing text between two dots try maybe
replaceFirst(String regex, String replacement)method on String object:regextells to search all characters between two dots (including these dots), soreplacementshould be “.hello.” (with dots).If your String will have more dots it will replace ALL characters between first and last dot. If you want regex to search for minimum number of characters necessary to satisfy the pattern you need to use Reluctant Quantifier ->
?like: