wishman
wishman

Reputation: 774

Regex Pattern to validate Numerical Value

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

Upvotes: 1

Views: 408

Answers (4)

Skinner
Skinner

Reputation: 1503

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

thanks rawling.

Upvotes: 0

Steven Stip
Steven Stip

Reputation: 387

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.

Upvotes: -1

Mena
Mena

Reputation: 48444

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

Upvotes: 3

m0skit0
m0skit0

Reputation: 25874

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

Upvotes: 4

Related Questions