Simply Regex is the simple builder API for building complex Regex. Extension libraries are the libraries which adds definitions of specific type of regex. Extensions make simply regex powerful as those definitions of different regex can simplify many challenging regex building in simple ways.
Simply Regex Datatype
Simply regex datatype is an extension library to simply regex which provides easy & simple ways to create regex for different datatypes like numbers or dates.
Number datatype
Creating regex for specific range of numbers is not easy using regex because regex is based on characters & we are expecting it to match as numbers. Building regex for specific number range from scratch is very time complex & can turn out to be buggy i.e. it might match number outside of range or might miss number within range etc.
With Simply Regex Datatype library, all you have to do is provide range of numbers & rest is taken care by library.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// import com.itsallbinary.simplyregex.datatype.SimpleDataTypeRegex.*; String ipRegex = regex().anywhereInText().def(number().between(0, 255).def()) .then().exactString(".") .then() .def(number().between(0, 255).def()) .then().exactString(".") .then().def(number().between(0, 255).def()) .then().exactString(".") .then().def(number().between(0, 255).def()).build(); Pattern pattern = Pattern.compile(ipRegex); boolean isMatch = pattern.matcher(input).matches(); |
This will build complex regex – ipRegex = ([0-9]|[1-9][0-9]|[1-1][0-9][0-9]|[2-2][0-4][0-9]|[2-2][5-5][0-5]|)\Q.\E([0-9]|[1-9][0-9]|[1-1][0-9][0-9]|[2-2][0-4][0-9]|[2-2][5-5][0-5]|)\Q.\E([0-9]|[1-9][0-9]|[1-1][0-9][0-9]|[2-2][0-4][0-9]|[2-2][5-5][0-5]|)\Q.\E([0-9]|[1-9][0-9]|[1-1][0-9][0-9]|[2-2][0-4][0-9]|[2-2][5-5][0-5]|)
Input: testString = “20.0.255.100” Output: isMatch = true
Input: testString = “20.0.256.100” Output: isMatch = false
Date datatype
Date is a datatype which can have many different formats in different use cases. This makes it challenging to have regex to exactly match the expected format. In java world formatting is handled using SimpleDateFormat which offers very wide variety of formats using specific Date and Time Patterns.
Simply regex datatype extension library provides easy way to build regex using same formats which are supported by SimpleDateFormat.
Example:
1 2 3 4 5 6 7 8 9 10 11 |
// import com.itsallbinary.simplyregex.datatype.SimpleDataTypeRegex.*; String regex = regex().anywhereInText().def(date().withDateFormat("MM/dd/yyyy").def()).build(); String input = "Today is 10/06/2018."; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); boolean isMatch = matcher.find(); String matchedDate = matcher.group(); assertEquals("Testing for regex = " + regex + " input =" + input, "10/06/2018", matchedDate); |