Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find if a string contains numbers followed by a specific string

I have a string like this:

String str = "Friday 1st August 2013"

I need to check: if the string contains "any number" followed by the "st" string, print "yes", else print "no".

I tried: if ( str.matches(".*\\dst") ) and if ( str.matches(".*\\d.st") ) but it doesn't work.

Any help?

like image 691
Frank Avatar asked Dec 20 '22 02:12

Frank


2 Answers

Use:

if ( str.matches(".*\\dst.*") )

String#matches() matches the regex pattern from beginning of the string to the end. The anchors ^ and $ are implicit. So, you should use the pattern that matches the complete string.

Or, use Pattern, Matcher and Matcher#find() method, to search for a particular pattern anywhere in a string:

Matcher matcher = Pattern.compile("\\dst").matcher(str);
if (matcher.find()) {
    // ok
}
like image 172
Rohit Jain Avatar answered Apr 27 '23 06:04

Rohit Jain


Regular expression can be used to match such pattern. e.g.

 String str = "Friday 1st August 2013"
    Pattern pattern = Pattern.compile("[0-9]+st");
    Matcher matcher = pattern.matcher(str);
    if(mathcer.find())
      //yes
    else
     //no
like image 28
nhrobin Avatar answered Apr 27 '23 06:04

nhrobin