简体   繁体   中英

Java: Delimiters and regular expressions

I'm using the scanner method to do work on a string and need to filter out junk

here's the sample string

5/31/1948@14:57

I need to strip out the / @ :

Theres this doc: http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html

But it's really confusing.

You can use the replaceAll method as:

String filetredStr = inputStr.replaceAll("[@/:]","");

And if you want to delete any non-digit you can do:

String filetredStr = inputStr.replaceAll("[^0-9]","");

如果您想将其拆分,请使用String#split()

String[] parts = "5/31/1948@14:57".split("[/@:]");

做这样的事情:

s.replaceAll("[\\/@:]", "");

An alternative to replaceAll(a,b) is as follows:

String str = "5/31/1948@14:57";
String charsToRemove = "/@:";
for (int i = 0; i < charsToRemove.length(); i++) {
    str = str.replace(charsToRemove.charAt(i)+"", "");
}

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