Question

I was wondering if anyone knew what the best method was to remove ordinal values in java when you don't know if the input is going to be either a single or double digit number?

i.e.

Input: 23rd

Expected output: 23


Input: 1st

Expected output: 1


So far, I tried using a combination of the regex util and the substring method:

String dayValue = "";
String dayPattern = "(?<=[0-9])(?:st|nd|rd|th)";
Pattern dPattern = Pattern.compile(dayPattern);
Matcher dMatch;

dayValue = "23rd";
dMatch = dPattern.matcher(dayValue);
System.out.println("The Pattern is: " + autoBuyDay.substring(dMatch.start()));

But that's just giving me a No match available error. Any ideas on how to modify this or a better way to go about accomplishing my goal here?

Was it helpful?

Solution

inputString.replaceAll("\\D", "");

Will remove all non-digit characters from the string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top