Replace everything except ONE single char

Viewed 227

I am dealing with some cells where I have to extract certain letters from these cells. I want to replace a whole String with " " except from one single-standing character. The biggest challenge to me has been to tell my Regex code only to look for a single Char and remove everything else. To further elaborate and simplify; I need my Regex to replace everything with "" execept from a single character that standa ALONE (I.E white spaces left and right or linked to a number)

public class Main {
    public static void main(String[] args) {
        String test = "22A 302 abc";
        String works = test.replaceAll("^\\w[\\s\\S]*", " ");
        System.out.println(works);
        //Desired result: A
    }
}
2 Answers

You could match a digit or space before and after capturing a char [A-Z].

In the replacement use group 1.

^.*[\d ]([A-Z])[ \d].*$

Regex demo | Java demo

If there can be only a single uppercase char in the string:

^[^A-Z]*[\d ]([A-Z])[ \d][^A-Z]*$

Regex demo

Example code

String test = "22A 302 abc";
String works = test.replaceAll("^.*[\\d ]([A-Z])[ \\d].*$", "$1");
System.out.println(works);

Output

A

To match between digits 0-9, horizontal whitespace chars or punctuations:

String works = test.replaceAll("^.*[\\p{P}0-9\\h]([A-Z])[\\p{P}0-9\\h].*$", "$1");

You can do it as follows:

public class Test {

    public static void main(String[] args) {
        String test = "22A 302 abc";
        String works = test.replaceAll("\\d+([A-Z]).*", "$1");
        System.out.println(works);
    }
}

Output:

A

Explanation: Replace everything with capturing group-1 ($1 in the code given above) which has just a letter A-Z preceded by an integer number(\\d+) and can have anything (.*) after it.

Related