TransWikia.com

Is there a way to find out how many numbers are at the end of a string without knowing the exact index?

Stack Overflow Asked by Hubi on February 1, 2021

I have a method that extracts a certain substring from a string. This substring consists of the numbers in the string. Then this is parsed to an integer.

Method:

protected int startIndex() throws Exception {
    String str = getWorkBook().getDefinedName("XYZ");
    String sStr = str.substring(10,13);

    return Integer.parseInt(sStr) - 1;
}

Example:

String :

‘0 DB’!$B$460

subString :

460

Well, I manually entered the index range for the substring. But I would like to automate it.

My approach:

String str = getWorkBook().getDefinedName("XYZ");
int length = str.length();
String sStr = str.substring(length - 3, length);

This works well for this example.

Now there is the problem that the numbers at the end of the string can also be 4 or 5 digits. If that is the case, I naturally get a NullPointerException.

Is there a way or another approach to find out how many numbers are at the end of the string?

5 Answers

If I were going to do this I just search from the end. This is quite efficient. It returns -1 if no positive number is found. Other return options and the use of an OptionalInt could also be used.

String s = "'0 DB'!$B$460";
int i;
for (i = s.length(); i > 0 && Character.isDigit(s.charAt(i-1)); i--);
int vv = (i < s.length()) ? Integer.valueOf(s.substring(i)) : -1;
System.out.println(vv);

Prints

460

If you know that there will always be a number at the end you can forget the ternary (?:) above and just do the following:

int vv = Integer.valueOf(s.substring(i));

Answered by WJS on February 1, 2021

Simple and fast solution without RegEx:

public class Main
{
    public static int getLastNumber(String str) {
        int index = str.length() - 1;
        while (index > 0 && Character.isDigit(str.charAt(index)))
            index--;
            
        return Integer.parseInt(str.substring(index + 1));        
    }
    
    public static void main(String[] args) {
        final String text = "'0 DB'!$B$460";
        System.out.println(getLastNumber(text));
    }
}

The output will be:

460

Answered by Ruslan Skaldin on February 1, 2021

If you just want to get the last number, you can go through the entire string on revert and get the start index:

protected static int startIndex() {
    String str = getWorkBook().getDefinedName("XYZ");

    if(Character.isDigit(str.charAt(str.length() - 1))) {
        for(int i = str.length() - 1; i >= 0; i--){
            if(!Character.isDigit(str.charAt(i)))
                return i+1;
        }
    }
    return -1;
}

and then print it:

public static void main(String[] args)  {
    int start = startIndex();
    if(start != -1)
       System.out.println(getWorkBook().getDefinedName("XYZ").substring(start));
   else 
      System.out.println("No Number found");
}

You will have to add the

Answered by dreamcrash on February 1, 2021

You can use the regex, (?<=D)d+$ which means one or more digits (i.e. d+) from the end of the string, preceded by non-digits (i.e. D).

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

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getNumber("'0 DB'!$B$460"));
    }

    static String getNumber(String str) {
        Matcher matcher = Pattern.compile("(?<=\D)\d+$").matcher(str);
        if (matcher.find()) {
            return matcher.group();
        }

        // If no match is found, return the string itself
        return str;
    }
}

Answered by Live and Let Live on February 1, 2021

In your case I would recommend to use regex with replaceAll like this:

String sStr = str.replaceAll(".*?([0-9]+)$", "$1");

This will extract the all the digits in the end or your String or any length.

Also I think you are missing the case when there are no digit in your String, for that I would recommend to check your string before you convert it to an Integer.

String sStr = str.replaceAll(".*?([0-9]+)$", "$1");
if (!sStr.isEmpty()) {
    return Integer.parseInt(sStr) - 1;    
}
return 0; // or any default value

Answered by YCF_L on February 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP