Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

What is RegEx Pattern (Regular Expression)? How to use it in Java? Example Attached

$
0
0

Crunchify Java Regular Expression Tutorial

What is RegEx?

Regular Expression is a search pattern for String. java.util.regex Classes for matching character sequences against patterns specified by regular expressions in Java.

You could use Regex for:

  • Searching Text
  • Extrating Text
  • Modifying Text

Let’s discuss some basic syntax:

Character Classes in Regex:

.  	Dot, any character (may or may not match line terminators, read on)
\d  	A digit: [0-9]
\D  	A non-digit: [^0-9]
\s  	A whitespace character: [ \t\n\x0B\f\r]
\S  	A non-whitespace character: [^\s]
\w  	A word character: [a-zA-Z_0-9]
\W  	A non-word character: [^\w]

 Quantifiers in Regex:

*      Match 0 or more times
+      Match 1 or more times
?      Match 1 or 0 times
{n}    Match exactly n times
{n,}   Match at least n times
{n,m}  Match at least n but not more than m times

Java Split also an Regex example.

Meta Characters in Regex:

\   	Escape the next meta-character (it becomes a normal/literal character)
^   	Match the beginning of the line
.   	Match any character (except newline)
$   	Match the end of the line (or before newline at the end)
|   	Alternation (‘or’ statement)
()  	Grouping
[]  	Custom character class

Let’s start working on example. In below example we will go over 5 diff Regex Examples.

  1. How to Parse uptime command result in Java
  2. Check if URL ends with specific extension
  3. Check if valid IP present
  4. Regex’s ReplaceAll() Example
  5. Find if SSN is valid

package crunchify.com.tutorial;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Crunchify.com
 *
 */

public class CrunchifyRegexTutorial {

	public static void main(String[] args) {
		crunchifyLoadAndAverageRegex();
		System.out.println("\n==========================\n");

		crunchifyFindUrlPattern();
		System.out.println("\n==========================\n");

		crunchifyFindIPMatcher();
		System.out.println("\n==========================\n");

		crunchifyRegexReplaceAllExample();
		System.out.println("\n==========================\n");

		crunchifyValidateSSN();
	}

	// Find if SSN is valid
	private static void crunchifyValidateSSN() {
		String ssn1 = "123-45-6789";
		String ssn2 = "123-456-789";
		String pattern = "^(\\d{3}-?\\d{2}-?\\d{4})$";

		if (ssn1.matches(pattern)) {
			System.out.println("SSN " + ssn1 + " is valid");
		} else {
			System.out.println("SSN " + ssn1 + " is NOT valid");
		}

		if (ssn2.matches(pattern)) {
			System.out.println("SSN " + ssn2 + " is valid");
		} else {
			System.out.println("SSN " + ssn2 + " is NOT valid");
		}

	}

	// ReplaceAll() Example
	private static void crunchifyRegexReplaceAllExample() {
		String find = "Java";
		String line = "This is Crunchify.com Java Tutorial.";
		String replace = "Spring MVC";

		Pattern p = Pattern.compile(find);
		Matcher m = p.matcher(line);

		// This line will find "Java" and replace it with "Spring MVC"
		line = m.replaceAll(replace);
		System.out.println(line);

	}

	// Check if valid IP present
	private static void crunchifyFindIPMatcher() {
		Pattern validIPPattern = Pattern.compile("^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$");
		System.out.println("192.abc.0.1 : " + validIPPattern.matcher("192.abc.0.1").find());
		System.out.println("192.168.0.1 : " + validIPPattern.matcher("192.168.0.1").find());
	}

	// Check if URL ends with specific extension
	private static void crunchifyFindUrlPattern() {
		String pattern = ".*\\.(ico|jpg|png|gif|tif|bmp|JPG|PNG|GIF|TIF|BMP)";
		Pattern r = Pattern.compile(pattern);

		Matcher m = r.matcher("https://cdn.crunchify.com/favicon.ico");
		if (m.find()) {
			System.out.println("URL pattern found");
		} else {
			System.out.println("URL pattern doesn't found");
		}

	}

	// How to Parse "uptime" command result in Java
	public static void crunchifyLoadAndAverageRegex() {
		Pattern uptimePattern = Pattern.compile("^.*\\s+load\\s+average:\\s+([\\d\\.]+),\\s+([\\d\\.]+),\\s+([\\d\\.]+)$");

		String output = " 10:17:32 up 189 days, 18:49,  5 user,  load average: 2.07, 1.11, 1.16";
		Matcher m = uptimePattern.matcher(output);

		if (m.matches()) {
			final double crunchify1MinuteLoadAvg = Double.parseDouble(m.group(1));
			final double crunchify5eMinuteloadAvg = Double.parseDouble(m.group(2));
			final double crunchify15MinuteLoadAvg = Double.parseDouble(m.group(3));

			System.out.println("Load Average 1 min: " + crunchify1MinuteLoadAvg);
			System.out.println("Load Average 5 min: " + crunchify5eMinuteloadAvg);
			System.out.println("Load Average 15 min: " + crunchify15MinuteLoadAvg);
		} else {
			System.out.println("no matches found");
		}

	}
}

Output:

Load Average 1 min: 2.07
Load Average 5 min: 1.11
Load Average 15 min: 1.16

==========================

URL pattern found

==========================

192.abc.0.1 : false
192.168.0.1 : true

==========================

This is Crunchify.com Spring MVC Tutorial.

==========================

SSN 123-45-6789 is valid
SSN 123-456-789 is NOT valid

How to validate Password strength using Java Code?

Find below my conditions:

#   			must contains one digit from 0-9
(?=.*[a-z])		must contains one lowercase characters
(?=.*[A-Z])		must contains one uppercase characters
(?=.*[!@#$%])	must contains one special symbols in the list "!@#$%"
.				match anything with previous condition checking
{8,25}			length at least 8 characters and maximum of 25

CrunchifyPasswordVerification.java

package crunchify.com.tutorial;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Crunchify.com
 *
 */
public class CrunchifyPasswordVerification {
	public static void main(String[] args) {

		String pattern = "((?=.*[@!#$%])(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,22})";
		Pattern r = Pattern.compile(pattern);

		List<String> input = new ArrayList<String>();
		input.add("Crunchify");
		input.add("Crunchify123#");
		input.add("crunchify123#");
		input.add("crunchify** ");
		input.add("Crunchify123!!");

		for (String password : input) {
			Matcher m = r.matcher(password);
			if (m.matches())
				System.out.println("Password: " + password + " is valid");
			else
				System.out.println("Password: " + password + " is NOT valid");
		}

	}
}

Result:

Password: Crunchify is NOT valid
Password: Crunchify123# is valid
Password: crunchify123# is NOT valid
Password: crunchify**  is NOT valid
Password: Crunchify123!! is valid

The post What is RegEx Pattern (Regular Expression)? How to use it in Java? Example Attached appeared first on Crunchify.


Viewing all articles
Browse latest Browse all 1037

Trending Articles