简体   繁体   中英

Using “%”, “?” and “#” in java to find a substring

I'm trying to go in a more effective way to find elements in a String different than having to convert the sentence into array of char and then comparing it against the other pieces of text, if you could please let me know if there is any other way you may know to do it,

What I need is

Boolean b = myString.contains(important%urgent);

and this should be different than:

Boolean b = myString.contains(urgent%important);

In the previous cases I want to get a True value if the words are contained in the String and they follow the specific order.

the next one is the ?

Boolean b myString.contains(friend?); //this would look for 'friend' and 'friends' or so

and the last one #

Boolean b myString.equals(#/#/2013 #:#:#);//this would return true if the date is in 2013

I hope I was able to explain myself, thanks for your answer.

You want regex!

To check word order:

Boolean b = myString.matches(".*important.*urgent.*");

Note, to be strict about "word" (ie to not match "unimportant"), add word boundaries:

Boolean b = myString.matches(".*\\bimportant\\b.*\\burgent\\b.*");

To check optional "s" at end of word:

Boolean b = myString.matches(".*friends?.*");

Again, to be strict and not match "friendly", add word boundaries:

Boolean b = myString.matches(".*\\bfriends?\\b.*");

To check for digits:

Boolean b = myString.matches("\\d+/\\d+/2013 \\d+:\\d+:\\d+");

Please try regular expression.

For example the last one:

Pattern p3 = Pattern.compile("^\d{2}/\d{2}/2013\s\d:\d:\d$");
Matcher m = p3.matcher(target);
if(m.matches()) {...}

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