Add regex to match numbers (integers and decimals)

This commit is contained in:
Adam Wojszczyk
2015-11-02 11:37:14 +01:00
parent dc90d82fd3
commit 7a852e1e33
2 changed files with 19 additions and 1 deletions

View File

@@ -9,10 +9,11 @@ class RegexPatterns {
private static final Pattern TRUE_OR_FALSE = Pattern.compile(/(true|false)/)
private static final Pattern ONLY_ALPHA_UNICODE = Pattern.compile(/[\p{L}]*/)
private static final Pattern NUMBER = Pattern.compile('-?\\d*(\\.\\d+)?')
private static final Pattern IP_ADDRESS = Pattern.compile('([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])');
private static final Pattern HOSTNAME_PATTERN = Pattern.compile('((http[s]?|ftp):\\/)\\/?([^:\\/\\s]+)(:[0-9]{1,5})?');
private static final Pattern EMAIL = Pattern.compile('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}');
private static final Pattern URL = Pattern.compile('((www\\.|(http|https|ftp|news|file)+\\:\\/\\/)[_.a-z0-9-]+\\.[a-z0-9\\/_:@=.+?,##%&~-]*[^.|\\\'|\\# |!|\\(|?|,| |>|<|;|\\)])');
private static final Pattern URL = Pattern.compile('((www\\.|(http|https|ftp|news|file)+\\:\\/\\/)[_.a-z0-9-]+\\.[a-z0-9\\/_:@=.+?,##%&~-]*[^.|\\\'|\\# |!|\\(|?|,| |>|<|;|\\)])')
String onlyAlphaUnicode() {
@@ -38,4 +39,8 @@ class RegexPatterns {
String url() {
return URL.pattern()
}
String number() {
return NUMBER.pattern()
}
}

View File

@@ -52,4 +52,17 @@ class RegexPatternsSpec extends Specification {
'ftp://asd.com:9090/asd/a?a=b' || true
'a.b.' || false
}
@Unroll
def "should generate a regex for a number [#textToMatch] that is a match [#shouldMatch]"() {
expect:
shouldMatch == Pattern.compile(regexPatterns.number()).matcher(textToMatch).matches()
where:
textToMatch || shouldMatch
'1' || true
'1.0' || true
'0.1' || true
'.1' || true
'1.' || false
}
}