Skip to content Skip to sidebar Skip to footer

Multiply Integers Inside A String By An Individual Value Using Regex

I currently have the code below and it successfully returns all the numbers that are present in a string I have. An example of the string would be say: 1 egg, 2 rashers of bacon, 3

Solution 1:

I've never tried this, but I think appendReplacement should solve your problem


Solution 2:

Doing arithmetic is a little complicated while doing the find()

Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(test);
int start = 0;
int end = 0;
StringBuffer resultString = new StringBuffer();
while (matcher.find()) {
    start = matcher.start();
    // Copy the string from the previous end to the start of this match
    resultString.append(test.substring(end, start));
    // Append the desired new value
    resultString.append(4 * Integer.parseInt(matcher.group()));
    end = matcher.end();
}
// Copy the string from the last match to the end of the string
resultString.append(test.substring(end));

This StringBuffer will hold the result you are expecting.


Post a Comment for "Multiply Integers Inside A String By An Individual Value Using Regex"