简体   繁体   中英

Split string to get an array of digits only (escaping white & empty spaces)

In my scenario, a string is given to my function and I should extract only the numbers and get rid of everything else.

Example inputs & their expected array output:

13/0003337/99  // Should output an array of "13", "0003337", "99"
13-145097-102  // Should output an array of "13", "145097", "102"
11   9727  76  // Should output an array of "11", "9727", "76"

In Qt/C++ I'd just do it as follows:

QString id = "13hjdhfj0003337      90";
QRegularExpression regex("[^0-9]");

QStringList splt = id.split(regex, QString::SkipEmptyParts);

if(splt.size() != 3) {
    // It is the expected input.
} else {
    // The id may have been something like "13 145097 102 92"
}

So with java I tried something similar but it didn't work as expected.

String id = "13 text145097 102"
String[] splt = id.split("[^0-9]");
ArrayList<String> idNumbers = new ArrayList<String>(Arrays.asList(splt));

Log.e(TAG, "ID numbers are: " + indexIDS.size());  // This logs more than 3 values, which isn't what I want.

So, what would be the best way to escape all spaces and characters except for the numbers [0-9] ?

Use [^0-9]+ as regex to make the regex match any positive number of non-digits.

id.split("[^0-9]+");

Output

[13, 145097, 102]

Edit

Since does not remove trailing the first empty String , if the String starts with non-digits, you need to manually remove that one, eg by using:

Pattern.compile("[^0-9]+").splitAsStream(id).filter(s -> !s.isEmpty()).toArray(String[]::new);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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