0

I am having a particular pattern of string

page0001
page0002
.
.
.
pageMN23
pageMN24
.
page0100
page0101

and so on

I have to remove "page" and zero's after that and then pick up the page number from that. and stroe that value. Here it will return both integer and string value for example "3","4" ,"MN23", MN24". What can be used so that correct value return and it get store in correctly.

2
  • simply str.replaceAll("page0","").split(" ")? Commented Feb 12, 2014 at 2:51
  • Doesn't replaceAll accept a regex? Commented Feb 12, 2014 at 2:59

2 Answers 2

2
test = test.replace("page", "");        
int x = Integer.parseInt(test);

Just replace all the occurrences of "page" with an empty string, then Integer.parseInt() takes care of the rest.

Sign up to request clarification or add additional context in comments.

2 Comments

If performance is an issue, you could equally use test = test.substring(4);. Less self-documenting though.
Thank you for support. But i have one more concern related to your answer. Here you have mentioned Integer variable to hold parsed value of "test". But few pages contain string for example "pageMO12". what can be done in that case.
1

Use this:

    String test = "page0100";
    boolean flag = false;
    int pageNo;
    try {
        test = test.replaceAll("page0*", ""); //Note the meta character * after 0. It removes all zeros exists after `page` string and before any non zero digit.
        pageNo = Integer.parseInt(test);
    } catch (NumberFormatException e) {
        // If NumberNumberFormatException caught here then `test` is string
        // NOT valid integer
        flag = true;
    }
    if (flag == false) {
        // Page Number is string
        // Use `test` variable here
    } else {
        // Page Number is integer
        // Use `pageNo` variable here
    }

1 Comment

test = test.replace("page", ""); is working fine but after that rest of part can be string or a int for example it can be "0003" or "MN23". so i can i differentiate it and store it in proper datatype variable and i have to use that single variable outside in code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.