1

I need to validate the following string to match only if the Number is greater than 0.

[D:\ifs\Pearl_Sync_Test\Client\Pub\Checkout\crm\source\crm\client\Ifs.SM.Common.MSOffice\Ifs.SM.Common.MSOffice.csproj]

47 Warning(s)
5 Error(s)

My solution so far is to match the above string

((\d)\sError\(s\))

Resulting in extracting this string, 5 Error(s)

So, is it possible to check if the Number is greater than 0 ?

Thanks

3
  • No it is not, this is just the part I wanted. I've updated the content Commented Jan 27, 2015 at 15:33
  • 1
    A bit unclear: Do you want to know a second regexp, in addition to yours, in order to find whether the number you extracted is greater than zero? Or do you want a regexp that improves yours, and will not match it at all if it is zero? And do you want to match the "Warnings" as well? Commented Jan 27, 2015 at 15:37
  • I just want to match 5 Error(s), and yes I need to improve my current Pattern. Not a second regex pattern. Thanks Commented Jan 27, 2015 at 15:42

4 Answers 4

4

Regular expressions are not really fit for this problem but assuming you will not get negative errors, you can just check if it's not 0.

"[1-9]\\d*\\sError\\(s\\)"

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

The answer you accepted was posted after mine, but anyway, glad to have helped :)
3

You can use the following regular expression idiom for error numbers that start with a digit > 1:

String[] errors = {"5 Error(s)", "50 Error(s)", "0 Error(s)"};
//                           | starts with digit > 0
//                           |    | optionally ends with 0 or more digits
//                           |    |    | rest of the pattern
Pattern p = Pattern.compile("[1-9]\\d* Error\\(s\\)");
for (String s: errors) {
    System.out.println(s.matches(p.pattern()));
}

Output

true
true
false

5 Comments

+ not really needed
Not that it really matters here, but [1-9]\\d* does the job too, and it's less catastrophic than [1-9]+\\d*.
@Rawing true, thanks for noticing. Although I fail to understand why "catastrophic"!
Because it can match strings like ` Error(s)`
@Mena: Reference to catastrophic backtracking.
0

[1-9][0-9]*\sError(s)?

thanks rawling.

1 Comment

The question mark does not make the second digit optional. It makes the + quantifier non-greedy. This won't match single digit numbers.
-1

in this case wouldn't you want to strip the errors bit off and check the value after you cast the first part to an int? It seems like you're trying to do string validation while you actually want to know what a certain number is.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.