Prasanna Kumar
Prasanna Kumar

Reputation: 3

Regular expression to limit number of digits

I am trying to write a regular expression that will only match with qtr1, qtr2, qtr3, qtr4 with help of following regex [q|qtr|qtrs|quarter]+[1-4] but the problem is if i ask something like this "Ficoscore for Q21 2005" a space is added between Q and 21 ie "Ficoscore for Q 21 2005" this not valid.

  String regEx = "([q|qtr|qtrs|quarter]+[1-4])";
  Pattern pattern = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
  Matcher matcher = pattern.matcher(userQuerySentence);
  System.out.println(matcher.matches());
  while (matcher.find()) {
     String quarterString = matcher.group();
     userQuerySentence = userQuerySentence.replaceAll(quarterString,
              (quarterString.substring(0, quarterString.length() - 1) + " " + quarterString.substring(quarterString
                       .length() - 1)));
  }

Upvotes: 0

Views: 94

Answers (1)

Toto
Toto

Reputation: 91385

[q|qtr|qtrs|quarter] is a character class, I guess you want (q|qtr|qtrs|quarter):

String regEx = "(?i)\\b((?:q(?:trs?|uarter)?)[1-4])\\b";

Upvotes: 1

Related Questions