How to remove remove to take only numerical values from string using regex java?

I have the following string:

   String textString = "Power for CH2 234 45";

I need a regex to remove white spaces between numbers but also want to avoid if there is a non-numeric value before a number like

String texString="23445";

Here want to avoid the numerical value after any non-numeric value Here in my String want to avoid the numeric value also after H there are 2 but I just want to make a string like “23445”.

Answer

You can use the regex, (?<!w)d+(?!w).

import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        // Test
        Stream.of(
                    "Power for CH2 234 45",
                    "Power for 2CH C2H CH2 234 45"
                ).forEach(s -> System.out.println(s + " => " + getNumber(s)));
    
    }
    static String getNumber(String textString) {
        return Pattern.compile("(?<!\w)\d+(?!\w)")
                .matcher(textString)
                .results()
                .map(MatchResult::group)
                .collect(Collectors.joining());
    }
}

Output:

Power for CH2 234 45 => 23445
Power for 2CH C2H CH2 234 45 => 23445

Non-Stream version:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // Test
        String[] testStrings = { "Power for CH2 234 45", "Power for 2CH C2H CH2 234 45" };

        for (String s : testStrings) {
            System.out.println(getNumber(s));
        }
    }

    static String getNumber(String textString) {
        StringBuilder sb = new StringBuilder();
        Matcher matcher = Pattern.compile("(?<!\w)\d+(?!\w)").matcher(textString);
        while (matcher.find()) {
            sb.append(matcher.group());
        }
        return sb.toString();
    }
}

Explanation of the regex at regex101:

enter image description here