简体   繁体   English

从字符串中提取子字符串

[英]Extract a substring from string

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. 在这里它将返回整数和字符串值,例如“ 3”,“ 4”,“ MN23”,MN24“。可以使用什么使正确的值返回并正确存储。

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. 只需用空字符串替换所有出现的“ page”,然后Integer.parseInt()负责其余的工作。

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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM