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

I have a line like this:

String str = "Friday 1st August 2013" 

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

I tried: if ( str.matches(".*\\dst") ) and if ( str.matches(".*\\d.st") ) , but it does not work.

Any help?

+4
source share
3 answers

Using:

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

String#matches() matches the regex pattern from the beginning of the line to the end. Anchors ^ and $ implicit. So you should use a pattern that matches the complete string.

Or use Pattern , Matcher and Matcher#find() to find a specific pattern anywhere in the line:

 Matcher matcher = Pattern.compile("\\dst").matcher(str); if (matcher.find()) { // ok } 
+9
source

A regular expression can be used to match that pattern. eg.

  String str = "Friday 1st August 2013" Pattern pattern = Pattern.compile("[0-9]+st"); Matcher matcher = pattern.matcher(str); if(mathcer.find()) //yes else //no 
+1
source

You can use this regex:

 .*?(\\d+)st.* 

? after * necessary because * is "greedy" (it will match the entire line). *? makes a non-greedy match. In addition, a number may have more than one digit (for example, β€œ15st”).

+1
source

Source: https://habr.com/ru/post/1493808/


All Articles