Remove leading trailing non-digit characters from a string in Java

I need to remove all leading and trailing characters from the string to the first and last digits, respectively.

Example: OBC9187A-1%A
Should return:9187A-1

How to achieve this in Java?

I understand that regex is a solution, but I am not good at it.
I tried this replaceAll("([^0-9.*0-9])","")
But it only returns numbers and strips of all alpha / special characters.

+4
source share
2 answers

Here is one example of use regexand javato solve your problem. I would suggest looking at some regular expression tutorial here - this is a nice option.

public static void main(String[] args) throws FileNotFoundException {
    String test = "OBC9187A-1%A";
    Pattern p = Pattern.compile("\\d.*\\d");
    Matcher m = p.matcher(test);

    while (m.find()) {
        System.out.println("Match: " + m.group());
    }
}

Conclusion:

Match: 9187A-1

\d .* - 0 \d . , \\d, , \ java, \ ... , -, . , / / , , . while , , . 1 , while if :

if(m.find()) 
{
    System.out.println("Match: " + m.group());
}
+2

s.

String s = "OBC9187A-1%A";
s = s.replaceAll("^\\D+", "").replaceAll("\\D+$", "");
System.out.println(s);
// prints 9187A-1

DEMO

Regex
^\D +

^ assert position at start of the string
\D+ match any character that not a digit [^0-9]
     Quantifier: + Between one and unlimited times, as many times as possible

\D + $

\D+ match any character that not a digit [^0-9]
     Quantifier: + Between one and unlimited times, as many times as possible
  $ assert position at end of the string
+2

All Articles