Showing posts with label Java Regex. Show all posts
Showing posts with label Java Regex. Show all posts

Email validation using Java Regex

📧 Email Validation Using Java Regular Expressions (Regex)

Topic: Java Regex Pattern for Email Validation


🧩 Overview

In this post, we’ll explore how to validate email addresses in Java using Regular Expressions (Regex).
The regex pattern enforces strict rules for valid email structures — ensuring only properly formatted email IDs are accepted.


🧠 Regex Pattern

^[A-Z0-9._]+@[A-Z0-9-]+\.[A-Z]{2,6}$

🔍 Pattern Breakdown

SymbolMeaningDescription
^Start of the patternEnsures the match begins from the start of the string
[A-Z0-9._]+First partThe local part (before @) must contain uppercase letters (A-Z), digits (0-9), and . or _
@SeparatorSeparates the username and domain parts
[A-Z0-9-]+Second partThe domain name (after @) must contain letters, digits, or hyphens (-)
\.[A-Z]{2,6}Third partThe domain extension must begin with a . followed by 2 to 6 letters (A-Z)
$End of the patternEnsures the match ends at the end of the string

🧩 In simple terms:

The email must look like USERNAME@DOMAIN.TLD,
where:

  • Username = letters, numbers, dots, or underscores

  • Domain = letters or numbers

  • TLD (Top-Level Domain) = 2–6 letters only (e.g., .com, .org, .co.in)


🧰 Java Implementation

Here’s the complete Java example to validate emails using this regex pattern.

package com.vinod.test; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author vinod.kumaran * * Simple email validator using Java Regular Expressions. * * Pattern: ^[A-Z0-9._]+@[A-Z0-9-]+\.[A-Z]{2,6}$ * * ^ = Start of pattern * [A-Z0-9._] = First part: allowed characters before '@' * @[A-Z0-9-] = Second part: allowed characters after '@' * \.[A-Z]{2,6} = Third part: domain extension with 2–6 letters * $ = End of pattern */ public class EmailValidator { // Compile the regex pattern (case-insensitive) public static final Pattern EMAIL_REGEX = Pattern.compile("^[A-Z0-9._]+@[A-Z0-9-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); public static void main(String[] args) { // Valid email System.out.println(validate("kkvinod@pretechsol.com")); // Invalid email: first part contains '%' System.out.println(validate("kkvin%od@pretechsol.com")); // Invalid email: second part contains '_' System.out.println(validate("kkvinod@prete_chsol.com")); // Invalid email: domain extension > 6 characters System.out.println(validate("kkvinod@pretechsol.comcomcom")); } // Validation method public static boolean validate(String emailAddress) { Matcher matcher = EMAIL_REGEX.matcher(emailAddress); return matcher.find(); } }

🧪 Sample Output

true false false false

✅ Explanation of Results

EmailExpected ResultReason
kkvinod@pretechsol.com✅ trueValid format
kkvin%od@pretechsol.com❌ false% not allowed before @
kkvinod@prete_chsol.com❌ false_ not allowed in domain name
kkvinod@pretechsol.comcomcom❌ falseTLD (extension) exceeds 6 letters 


Different representation of IPV4 in Java

🌐 IPv4 Address — Different Representations & Normalization Using Java

When working with networks, operating systems, or low-level protocols, an IPv4 address may not always appear in the familiar dotted-decimal form like:

192.0.2.235

An IPv4 address is fundamentally a 32-bit integer, and therefore it can be represented in multiple notations:

Representation FormatExampleDescription
Dotted Decimal192.0.2.235Standard human-friendly format
Dotted Hexadecimal0xC0.0x00.0x02.0xEBEach octet represented in base-16
Dotted Octal0300.0000.0002.0353Each octet represented in base-8
Hexadecimal (no dots)0xC00002EBFull 32-bit value as a single hex number
Decimal (no dots)3221226219Full 32-bit value represented as decimal
Octal (no dots)030000001353Full 32-bit value represented as octal

👉 All of the above represent the same IPv4 address:

192.0.2.235


🧠 Why does this matter?

Some operating systems, browsers, and networking libraries accept alternative representations of IP addresses.
This can be exploited:

  • To evade security filters (firewalls, validation rules).

  • To bypass URL allow/block lists (e.g., app allows only whitelisted domain IP).

Example:

http://0xC00002EB → interpreted internally as 192.0.2.235

✅ Java Program — Normalize any IPv4 Representation

The following Java program accepts an IPv4 address in any supported notation (hex, octal, dotted, decimal), normalizes it, and prints it back in standard dotted decimal format.

package com.pretech; import java.net.URL; import java.util.StringTokenizer; import java.util.regex.Pattern; public class Ipv4Example { private static final Pattern IPV4REGEX = Pattern.compile( "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b" ); public static void main(String[] args) { try { System.out.println(createHostAddress("http://192.0.2.235")); System.out.println(createHostAddress("http://0xC0.0x00.0x02.0xEB")); System.out.println(createHostAddress("http://0300.0000.0002.0353")); System.out.println(createHostAddress("http://0xC00002EB")); System.out.println(createHostAddress("http://030000001353")); } catch (Exception e) { e.printStackTrace(); } } private static String createHostAddress(final String url) throws Exception { URL urldetails = new URL(url); String addr = urldetails.getHost(); boolean validHost = true; StringBuffer hostStringBuffer = new StringBuffer(); try { StringTokenizer hostTokenizer = new StringTokenizer(addr, "."); int tokenCount = hostTokenizer.countTokens(); // Case 1: nondotted hex or decimal number format if (isNumber(addr) && tokenCount == 1) { long decimalIpAddress = Long.decode(addr); hostStringBuffer.append(longToIpAddress(decimalIpAddress)); if (!IPV4REGEX.matcher(hostStringBuffer.toString()).matches()) { validHost = false; } // Case 2: dotted hex or dotted octal representation } else if (isNumber(addr) && tokenCount > 1) { int i = 0; while (hostTokenizer.hasMoreTokens()) { String token = hostTokenizer.nextToken(); hostStringBuffer.append(Integer.toString(Integer.decode(token))); if (i < 3) { hostStringBuffer.append("."); } i++; } if (!IPV4REGEX.matcher(hostStringBuffer.toString()).matches()) { validHost = false; } } else { // Other host formats hostStringBuffer.append(addr); } if (!validHost) { throw new Exception("Invalid Host name"); } } catch (Exception e) { throw new Exception("Invalid Host name: " + e.getMessage(), e); } return hostStringBuffer.toString(); } // Convert long format to dotted decimal IP public static String longToIpAddress(long ipAddress) { StringBuilder ipStringBuffer = new StringBuilder(); for (int i = 0; i < 4; i++) { ipStringBuffer.insert(0, Long.toString(ipAddress & 0xff)); if (i < 3) { ipStringBuffer.insert(0, '.'); } ipAddress >>= 8; } return ipStringBuffer.toString(); } private static boolean isNumber(final String addr) { try { StringTokenizer addrTokenizer = new StringTokenizer(addr, "."); while (addrTokenizer.hasMoreTokens()) { String token = addrTokenizer.nextToken(); Long.decode(token); // detects hex (0x..), octal (0..), decimal } return true; } catch (Exception e) { return false; } } }

🖨 Output

192.0.2.235 192.0.2.235 192.0.2.235 192.0.2.235 192.0.2.235

IPV6 Java Regular expression example

Pattern

private static final Pattern IPV6REGEX = Pattern.compile(""
+ "^(((?=(?>.*?::)(?!.*::)))(::)?([0-9A-F]{1,4}::?){0,5}"
+ "|([0-9A-F]{1,4}:){6})(\\2([0-9A-F]{1,4}(::?|$)){0,2}|((25[0-5]"
+ "|(2[0-4]|1\\d|[1-9])?\\d)(\\.|$)){4}|[0-9A-F]{1,4}:[0-9A-F]{1,"
+ "4})(?<![^:]:|\\.)\\z", Pattern.CASE_INSENSITIVE);

Example

package com.pretech;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

public class Ipv6Example {
private static final Pattern IPV6REGEX = Pattern.compile(
"" + "^(((?=(?>.*?::)(?!.*::)))(::)?([0-9A-F]{1,4}::?){0,5}"
+ "|([0-9A-F]{1,4}:){6})(\\2([0-9A-F]{1,4}(::?|$)){0,2}|((25[0-5]"
+ "|(2[0-4]|1\\d|[1-9])?\\d)(\\.|$)){4}|[0-9A-F]{1,4}:[0-9A-F]{1,"
+ "4})(?<![^:]:|\\.)\\z",
Pattern.CASE_INSENSITIVE);

public static void main(String[] args) {

URL url;
int i1, i2;

try {
url = new URL("http://[FF01:0:0:0:0:0:0:0101]");
String originalHostName = url.getHost();

System.out.println(originalHostName);
if (originalHostName.startsWith("[") && originalHostName.endsWith("]")) {

i1 = originalHostName.indexOf("[");

originalHostName = originalHostName.substring(i1 + 1);

i2 = originalHostName.lastIndexOf("]");

originalHostName = originalHostName.substring(0, i2);

if (IPV6REGEX.matcher(originalHostName).matches()) {

System.out.println(url + " is a ipv6 address");
String hostName = InetAddress.getByName(originalHostName).getHostAddress().toLowerCase();
if (hostName.contains(":")) {
hostName = "[" + hostName + "]";
}

}
}

} catch (MalformedURLException | UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

Output

[FF01:0:0:0:0:0:0:0101]
http://[FF01:0:0:0:0:0:0:0101] is a ipv6 address

Java Regex Date Validation Example


Java Regex Date Validation Example

Date Regex Pattern

 
(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)
 
     (
start of group =1
 0?[1-9]
01-09 or 1-9
 |           
..or
 [12][0-9]
10-19 or 20-29
 |
..or
 3[01]
30, 31
 )
end of group =1
 /
follow by a "/"
 (
start of group =2
 0?[1-9]
01-09 or 1-9
 |
..or
 1[012]
10,11,12
 )
end of group =2
 /
follow by a "/"
 (
start of group =3
(19|20)\\d\\d
19[0-9][0-9] or 20[0-9][0-9]
 )
end of group =3
 
Example
package mycollectiontest;

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

public class RegexExample {
private Pattern pattern;
private Matcher matcher;

private static final String DATE_PATTERN = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";

public RegexExample() {
pattern = Pattern.compile(DATE_PATTERN);
String input = "1/1/2012";
System.out.println("input : " + input + " " + validate(input));

String input1 = "32/13/2010";
System.out.println("input : " + input1 + " " + validate(input1));
}

public boolean validate(final String date) {
matcher = pattern.matcher(date);

if (matcher.matches()) {

matcher.reset();

if (matcher.find()) {
String day = matcher.group(1);
String month = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));
if (day.equals("31") && (month.equals("4") || month.equals("6") || month.equals("9") || month.equals("11")
|| month.equals("04") || month.equals("06") || month.equals("09"))) {
return false; // only 1,3,5,7,8,10,12 has 31 days
} else if (month.equals("2") || month.equals("02")) {
// leap year
if (year % 4 == 0) {
if (day.equals("30") || day.equals("31")) {
return false;
} else {
return true;
}
} else {
if (day.equals("29") || day.equals("30") || day.equals("31")) {
return false;
} else {
return true;
}
}
} else {
return true;
}
} else {
return false;
}
} else {
return false;
}
}

public static void main(String[] args) {
new RegexExample();
}
}
Output

input :  1/1/2012   true
input : 32/13/2010 false
 

Java Regex IP Address Validation Example

IP Address Regex Pattern

^([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])$
^
Start of line
(
Start of group
[01]?\\d\\d?
Can be one or two digits. If three digits appear, it must start either 0 or 1
2[0-4]\\d 
start with 2, follow by 0-4 and end with any digit
25[0-5]
start with 2, follow by 5 and end with 0-5 (25[0-5])
)
End of group
\.
follow by a dot
end of the line
 

Example

package mycollectiontest;

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

public class RegexExample {
private Pattern pattern;
private Matcher matcher;
private static final String IPADDRESS_PATTERN = "^([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])$";

public RegexExample() {
pattern = Pattern.compile(IPADDRESS_PATTERN);
String input = "12.12.12";
System.out.println("input : " + input + " " + validate(input));

String input1 = "180.151.46.166";
System.out.println("input : " + input1 + " " + validate(input1));
}

public boolean validate(final String username) {
matcher = pattern.matcher(username);
return matcher.matches();

}

public static void main(String[] args) {
new RegexExample();
}
}
Output
input :  12.12.12   false
input :  180.151.46.166   true

Java Regex Username Password example

Java Regex Username Password examples

User name Regex Pattern

^[a-z0-9_-]{3,15}$
Split this pattern
^
Start of the line
[a-z0-9_-]
Match characters and symbols in the list, a-z, 0-9 , underscore , hyphen
{3,15}
Length at least 3 characters and maximum length of 15
$
End of the line

Password Regular Expression Pattern

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})
 
(
Start of group
(?=.*\d)
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
{6,20}
length at least 6 characters and maximum of 20
)
End of group
 

Example

package mycollectiontest;

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

public class RegexExample {
private Pattern pattern;
private Matcher matcher;
private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";
private static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";

public RegexExample() {
pattern = Pattern.compile(USERNAME_PATTERN);
System.out.println("input : pretech user name " + validate("pretech"));
pattern = Pattern.compile(PASSWORD_PATTERN);
System.out.println("input : password " + validate("pretech@gmail.com"));
}

public boolean validate(final String username) {

matcher = pattern.matcher(username);
return matcher.matches();
}

public static void main(String[] args) {
new RegexExample();
}
}

Output

 
input : pretech user name true
input : password    false

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts