What is Regex?
Regular Expression (Regex) is a powerful tool for finding or replacing specific patterns in strings. Both Java and JavaScript support regex for data validation, searching, transformation, and more.
Comprehensive Regex Guide
Regular Expression is a powerful tool for searching and manipulating string patterns. This guide will help you understand regex from basic concepts to advanced patterns.
Regex Structure
// Literal syntax - pattern between slashes (/)
const regex1 = /pattern/flags;
// Constructor syntax
const regex2 = new RegExp("pattern", "flags");
// Using String pattern
String pattern = "pattern";
Pattern regex = Pattern.compile(pattern, flags);
// Direct Pattern object creation
Pattern regex = Pattern.compile("pattern");
Regex Methods
// Regex methods
str.match(/regex/flags) // Returns matches as an array
str.replace(/regex/, "replacement") // Replaces matches with replacement string
str.split(/regex/) // Splits string at matches into an array
/regex/.test(str) // Returns true if match found, false otherwise
/regex/.exec(str) // Returns first match as an array
// Examples
const str = "Hello world 123";
str.match(/\d+/g); // ["123"]
str.replace(/world/, "JS"); // "Hello JS 123"
/Hello/.test(str); // true
// Java regex methods
String str = "Hello world 123";
// Check for match
boolean isMatch = str.matches(".*\\d+.*"); // true
// Find matches
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group()); // Prints "123"
}
// Replace string
String replaced = str.replaceAll("world", "Java"); // "Hello Java 123"
// Split string
String[] parts = str.split("\\s"); // ["Hello", "world", "123"]
Regex Flags
Flag | Description | JavaScript | Java |
---|---|---|---|
g | Global search - find all matches | /pattern/g | Pattern.MULTILINE |
m | Multiline search - search across multiple lines | /pattern/m | Pattern.MULTILINE |
i | Case-insensitive search | /pattern/i | Pattern.CASE_INSENSITIVE |
s | Allow . to match newline characters | /pattern/s | Pattern.DOTALL |
u | Unicode support | /pattern/u | - |
y | Sticky mode - search at specific position | /pattern/y | - |
g: Global Search Example
const str = "apple banana apple";
// Without g flag - returns only first match
str.match(/apple/); // ["apple"]
// With g flag - returns all matches
str.match(/apple/g); // ["apple", "apple"]
String str = "apple banana apple";
Pattern pattern = Pattern.compile("apple");
Matcher matcher = pattern.matcher(str);
// Find all matches
List matches = new ArrayList<>();
while (matcher.find()) {
matches.add(matcher.group());
}
System.out.println(matches); // [apple, apple]
Regex Symbol Reference
Symbol | Description | Example |
---|---|---|
. |
Matches any character except newline | /a.c/ - matches "abc", "a1c", etc. |
^ |
Start of string | /^Hello/ - matches "Hello world" |
$ |
End of string | /world$/ - matches "Hello world" |
\d |
Digit [0-9] | /\d{3}/ - matches "123", "456", etc. |
\w |
Word character [A-Za-z0-9_] | /\w+/ - matches "Hello_123" |
\s |
Whitespace (space, tab, newline) | /a\sb/ - matches "a b" |
\b |
Word boundary | /\bworld\b/ - matches "world" in "Hello world" |
Regex Quantifiers
Symbol | Description | Example |
---|---|---|
* |
0 or more | /a*/ - matches "", "a", "aa", "aaa", etc. |
+ |
1 or more | /a+/ - matches "a", "aa", "aaa", etc. |
? |
0 or 1 | /colou?r/ - matches "color", "colour" |
{n} |
Exactly n times | /\d{3}/ - matches "123", "456", etc. |
{n,} |
n or more times | /\d{2,}/ - matches "12", "123", "1234", etc. |
{n,m} |
Between n and m times | /\d{2,4}/ - matches "12", "123", "1234" |
Regex Grouping Patterns
// 1. Basic Grouping
const regex = /(abc)+/; // 'abc' repeated one or more times
"abcabc".match(regex); // ["abcabc", "abc"]
// 2. Capturing Groups
const dateRegex = /(\d{4})-(\d{2})-(\d{2})/;
const result = "2023-05-15".match(dateRegex);
// result = ["2023-05-15", "2023", "05", "15"]
// result[1] = "2023", result[2] = "05", result[3] = "15"
// 3. Non-capturing Groups (?:)
const nonCapture = /(?:abc)(\d+)/;
const matches = "abc123".match(nonCapture);
// matches = ["abc123", "123"]
// First group 'abc' is not captured
// 1. Basic Grouping
Pattern pattern = Pattern.compile("(abc)+");
Matcher matcher = pattern.matcher("abcabc");
matcher.find();
System.out.println(matcher.group(0)); // "abcabc"
System.out.println(matcher.group(1)); // "abc"
// 2. Capturing Groups
Pattern datePattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher dateMatcher = datePattern.matcher("2023-05-15");
dateMatcher.find();
// dateMatcher.group(0) = "2023-05-15"
// dateMatcher.group(1) = "2023"
// dateMatcher.group(2) = "05"
// dateMatcher.group(3) = "15"
// 3. Non-capturing Groups (?:)
Pattern nonCapture = Pattern.compile("(?:abc)(\\d+)");
Matcher ncMatcher = nonCapture.matcher("abc123");
ncMatcher.find();
System.out.println(ncMatcher.group(0)); // "abc123"
System.out.println(ncMatcher.group(1)); // "123"
// First group 'abc' is not captured
Email Validation
This regex validates email addresses based on common email format patterns.
function validateEmail(email) {
const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return regex.test(email);
}
console.log(validateEmail("example@domain.com")); // true
console.log(validateEmail("invalid.email@")); // false
public class EmailValidator {
public static boolean validateEmail(String email) {
String regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
return email.matches(regex);
}
public static void main(String[] args) {
System.out.println(validateEmail("example@domain.com")); // true
System.out.println(validateEmail("invalid.email@")); // false
}
}
Phone Number Validation
This regex validates Korean phone number format. Example: 010-1234-5678
function validatePhone(phone) {
const regex = /^010-\d{4}-\d{4}$/;
return regex.test(phone);
}
console.log(validatePhone("010-1234-5678")); // true
console.log(validatePhone("011-123-4567")); // false
public class PhoneValidator {
public static boolean validatePhone(String phone) {
String regex = "^010-\\d{4}-\\d{4}$";
return phone.matches(regex);
}
public static void main(String[] args) {
System.out.println(validatePhone("010-1234-5678")); // true
System.out.println(validatePhone("011-123-4567")); // false
}
}
Extract Numbers
This regex extracts only numbers from a string.
function extractNumbers(str) {
return str.match(/\d+/g)?.join("") || "";
}
console.log(extractNumbers("abc123def456")); // "123456"
console.log(extractNumbers("no numbers")); // ""
public class NumberExtractor {
public static String extractNumbers(String str) {
return str.replaceAll("[^0-9]", "");
}
public static void main(String[] args) {
System.out.println(extractNumbers("abc123def456")); // "123456"
System.out.println(extractNumbers("no numbers")); // ""
}
}
Extract English
This regex extracts only English letters from a string.
function extractEnglish(str) {
return str.match(/[a-zA-Z]+/g)?.join("") || "";
}
console.log(extractEnglish("hello안녕123world")); // "helloworld"
console.log(extractEnglish("123가나다")); // ""
public class EnglishExtractor {
public static String extractEnglish(String str) {
return str.replaceAll("[^a-zA-Z]", "");
}
public static void main(String[] args) {
System.out.println(extractEnglish("hello안녕123world")); // "helloworld"
System.out.println(extractEnglish("123가나다")); // ""
}
}
Remove Special Characters
This regex removes special characters from a string.
function removeSpecialChars(str) {
return str.replace(/[^a-zA-Z0-9가-힣\s]/g, "");
}
console.log(removeSpecialChars("hello@world! 안녕#")); // "helloworld 안녕"
console.log(removeSpecialChars("@#$%")); // ""
public class SpecialCharRemover {
public static String removeSpecialChars(String str) {
return str.replaceAll("[^a-zA-Z0-9가-힣\\s]", "");
}
public static void main(String[] args) {
System.out.println(removeSpecialChars("hello@world! 안녕#")); // "helloworld 안녕"
System.out.println(removeSpecialChars("@#$%")); // ""
}
}
Remove Whitespace
Various methods to remove whitespace from strings.
// Remove all whitespace (spaces, tabs, newlines)
function removeAllSpaces(str) {
return str.replace(/\s/g, "");
}
// Remove whitespace from both ends only
function trimSpaces(str) {
return str.replace(/^\s+|\s+$/g, "");
// Or use the built-in method
// return str.trim();
}
// Normalize multiple spaces to single spaces
function normalizeSpaces(str) {
return str.replace(/\s+/g, " ");
}
const text = " Hello World \n ";
console.log(removeAllSpaces(text)); // "HelloWorld"
console.log(trimSpaces(text)); // "Hello World"
console.log(normalizeSpaces(text)); // " Hello World "
public class SpaceRemover {
// Remove all whitespace (spaces, tabs, newlines)
public static String removeAllSpaces(String str) {
return str.replaceAll("\\s", "");
}
// Remove whitespace from both ends only
public static String trimSpaces(String str) {
return str.replaceAll("^\\s+|\\s+$", "");
// Or use the built-in method
// return str.trim();
}
// Normalize multiple spaces to single spaces
public static String normalizeSpaces(String str) {
return str.replaceAll("\\s+", " ");
}
public static void main(String[] args) {
String text = " Hello World \n ";
System.out.println(removeAllSpaces(text)); // "HelloWorld"
System.out.println(trimSpaces(text)); // "Hello World"
System.out.println(normalizeSpaces(text)); // " Hello World "
}
}
String Padding (Lpadding, Rpadding)
Fill the left or right side of a string with specific characters to create a string of specified length.
// Left padding (Lpadding)
function leftPad(str, length, char = ' ') {
return str.length >= length ? str : new Array(length - str.length + 1).join(char) + str;
}
// Or use ES2017's padStart method
function leftPadES2017(str, length, char = ' ') {
return str.padStart(length, char);
}
// Right padding (Rpadding)
function rightPad(str, length, char = ' ') {
return str.length >= length ? str : str + new Array(length - str.length + 1).join(char);
}
// Or use ES2017's padEnd method
function rightPadES2017(str, length, char = ' ') {
return str.padEnd(length, char);
}
const num = "42";
console.log(leftPad(num, 5, '0')); // "00042"
console.log(leftPadES2017(num, 5, '0')); // "00042"
console.log(rightPad(num, 5, '0')); // "42000"
console.log(rightPadES2017(num, 5, '0')); // "42000"
public class StringPadder {
// Left padding (Lpadding)
public static String leftPad(String str, int length, char padChar) {
if (str.length() >= length) {
return str;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length - str.length(); i++) {
sb.append(padChar);
}
sb.append(str);
return sb.toString();
}
// Java 11+ offers repeat() method
public static String leftPadJava11(String str, int length, char padChar) {
if (str.length() >= length) {
return str;
}
return String.valueOf(padChar).repeat(length - str.length()) + str;
}
// Right padding (Rpadding)
public static String rightPad(String str, int length, char padChar) {
if (str.length() >= length) {
return str;
}
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < length - str.length(); i++) {
sb.append(padChar);
}
return sb.toString();
}
// Java 11+ offers repeat() method
public static String rightPadJava11(String str, int length, char padChar) {
if (str.length() >= length) {
return str;
}
return str + String.valueOf(padChar).repeat(length - str.length());
}
public static void main(String[] args) {
String num = "42";
System.out.println(leftPad(num, 5, '0')); // "00042"
// System.out.println(leftPadJava11(num, 5, '0')); // "00042" (Java 11+)
System.out.println(rightPad(num, 5, '0')); // "42000"
// System.out.println(rightPadJava11(num, 5, '0')); // "42000" (Java 11+)
}
}
URL Detection
Extract and validate URLs from text.
// Pattern for general URL detection
const urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g;
// Simpler pattern for common URLs
const simpleUrlRegex = /https?:\/\/\S+/g;
// Function to extract URLs from text
function extractUrls(text) {
return text.match(urlRegex) || [];
}
// Function to validate if a string is a valid URL
function isValidUrl(url) {
return urlRegex.test(url);
}
// Examples
const text = "Visit https://example.com and http://github.com/user/repo for more info.";
console.log(extractUrls(text));
// ["https://example.com", "http://github.com/user/repo"]
console.log(isValidUrl("https://example.com")); // true
console.log(isValidUrl("not-a-url")); // false
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UrlExtractor {
// Pattern for general URL detection
private static final String URL_REGEX = "https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)";
private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX);
// Extract URLs from text
public static List extractUrls(String text) {
List urls = new ArrayList<>();
Matcher matcher = URL_PATTERN.matcher(text);
while (matcher.find()) {
urls.add(matcher.group());
}
return urls;
}
// Validate if a string is a valid URL
public static boolean isValidUrl(String url) {
return URL_PATTERN.matcher(url).matches();
}
public static void main(String[] args) {
String text = "Visit https://example.com and http://github.com/user/repo for more info.";
List urls = extractUrls(text);
System.out.println(urls);
// [https://example.com, http://github.com/user/repo]
System.out.println(isValidUrl("https://example.com")); // true
System.out.println(isValidUrl("not-a-url")); // false
}
}
Date Format Validation
Validate and extract dates in various formats.
// YYYY-MM-DD format (ISO)
const isoDateRegex = /^\d{4}-\d{2}-\d{2}$/;
// MM/DD/YYYY format (US)
const usDateRegex = /^(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])\/\d{4}$/;
// DD/MM/YYYY format (UK/EU)
const euDateRegex = /^(0[1-9]|[12]\d|3[01])\/(0[1-9]|1[0-2])\/\d{4}$/;
// Function to validate dates in different formats
function validateDate(date, format = 'iso') {
switch(format) {
case 'iso':
return isoDateRegex.test(date);
case 'us':
return usDateRegex.test(date);
case 'eu':
return euDateRegex.test(date);
default:
return false;
}
}
// Function to extract dates from text
function extractDates(text) {
// Combined pattern for common date formats
const datePattern = /\b(\d{4}-\d{2}-\d{2}|\d{1,2}\/\d{1,2}\/\d{4}|\d{1,2}-\d{1,2}-\d{4})\b/g;
return text.match(datePattern) || [];
}
// Examples
console.log(validateDate("2023-01-15", "iso")); // true
console.log(validateDate("01/15/2023", "us")); // true
console.log(validateDate("15/01/2023", "eu")); // true
const text = "Meeting on 2023-01-15 and deadline is 02/28/2023.";
console.log(extractDates(text)); // ["2023-01-15", "02/28/2023"]
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateValidator {
// YYYY-MM-DD format (ISO)
private static final Pattern ISO_DATE_PATTERN = Pattern.compile("^\\d{4}-\\d{2}-\\d{2}$");
// MM/DD/YYYY format (US)
private static final Pattern US_DATE_PATTERN =
Pattern.compile("^(0[1-9]|1[0-2])\\/(0[1-9]|[12]\\d|3[01])\\/\\d{4}$");
// DD/MM/YYYY format (UK/EU)
private static final Pattern EU_DATE_PATTERN =
Pattern.compile("^(0[1-9]|[12]\\d|3[01])\\/(0[1-9]|1[0-2])\\/\\d{4}$");
// Combined pattern for extraction
private static final Pattern ANY_DATE_PATTERN =
Pattern.compile("\\b(\\d{4}-\\d{2}-\\d{2}|\\d{1,2}\\/\\d{1,2}\\/\\d{4}|\\d{1,2}-\\d{1,2}-\\d{4})\\b");
// Validate date string against a specific format
public static boolean validateDate(String date, String format) {
switch(format) {
case "iso":
return ISO_DATE_PATTERN.matcher(date).matches();
case "us":
return US_DATE_PATTERN.matcher(date).matches();
case "eu":
return EU_DATE_PATTERN.matcher(date).matches();
default:
return false;
}
}
// Extract dates from text
public static List extractDates(String text) {
List dates = new ArrayList<>();
Matcher matcher = ANY_DATE_PATTERN.matcher(text);
while (matcher.find()) {
dates.add(matcher.group());
}
return dates;
}
public static void main(String[] args) {
System.out.println(validateDate("2023-01-15", "iso")); // true
System.out.println(validateDate("01/15/2023", "us")); // true
System.out.println(validateDate("15/01/2023", "eu")); // true
String text = "Meeting on 2023-01-15 and deadline is 02/28/2023.";
System.out.println(extractDates(text)); // [2023-01-15, 02/28/2023]
}
}
HTML Tag Removal
Remove HTML tags from strings, keeping only the text content.
// Simple HTML tag removal
function stripHtmlTags(html) {
return html.replace(/<[^>]*>/g, '');
}
// HTML tag removal with handling for entities
function stripHtmlTagsAndEntities(html) {
// First replace common HTML entities
const withoutEntities = html
.replace(/ /g, ' ')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'");
// Then remove all HTML tags
return withoutEntities.replace(/<[^>]*>/g, '');
}
// Examples
const htmlContent = "This is bold and italic text with a link.
";
console.log(stripHtmlTags(htmlContent));
// "This is bold and italic text with a link."
const htmlWithEntities = "This & that with "quotes" and a <tag>.
";
console.log(stripHtmlTagsAndEntities(htmlWithEntities));
// "This & that with "quotes" and a ."
public class HtmlTagRemover {
// Simple HTML tag removal
public static String stripHtmlTags(String html) {
return html.replaceAll("<[^>]*>", "");
}
// HTML tag removal with handling for entities
public static String stripHtmlTagsAndEntities(String html) {
// First replace common HTML entities
String withoutEntities = html
.replaceAll(" ", " ")
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll(""", "\"")
.replaceAll("'", "'");
// Then remove all HTML tags
return withoutEntities.replaceAll("<[^>]*>", "");
}
public static void main(String[] args) {
String htmlContent = "This is bold and italic text with a link.
";
System.out.println(stripHtmlTags(htmlContent));
// "This is bold and italic text with a link."
String htmlWithEntities = "This & that with "quotes" and a <tag>.
";
System.out.println(stripHtmlTagsAndEntities(htmlWithEntities));
// "This & that with "quotes" and a ."
}
}
IP Address (IPv4) Validation
Validate and extract IPv4 addresses.
// IPv4 address pattern
const ipv4Regex = /\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/;
// Function to validate an IPv4 address
function isValidIpv4(ip) {
return ipv4Regex.test(ip);
}
// Function to extract IPv4 addresses from text
function extractIpv4Addresses(text) {
const ipRegex = new RegExp(ipv4Regex.source, 'g');
return text.match(ipRegex) || [];
}
// Examples
console.log(isValidIpv4("192.168.1.1")); // true
console.log(isValidIpv4("255.255.255.255")); // true
console.log(isValidIpv4("256.256.256.256")); // false (invalid values)
console.log(isValidIpv4("192.168.1")); // false (incomplete)
const networkLog = "Client 192.168.1.5 connected to server 10.0.0.1 via gateway 192.168.1.1";
console.log(extractIpv4Addresses(networkLog));
// ["192.168.1.5", "10.0.0.1", "192.168.1.1"]
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPv4Validator {
// IPv4 address pattern
private static final String IPV4_PATTERN =
"\\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";
private static final Pattern IPV4_REGEX = Pattern.compile(IPV4_PATTERN);
// Validate an IPv4 address
public static boolean isValidIpv4(String ip) {
return IPV4_REGEX.matcher(ip).matches();
}
// Extract IPv4 addresses from text
public static List extractIpv4Addresses(String text) {
List ipAddresses = new ArrayList<>();
Matcher matcher = IPV4_REGEX.matcher(text);
while (matcher.find()) {
ipAddresses.add(matcher.group());
}
return ipAddresses;
}
public static void main(String[] args) {
System.out.println(isValidIpv4("192.168.1.1")); // true
System.out.println(isValidIpv4("255.255.255.255")); // true
System.out.println(isValidIpv4("256.256.256.256")); // false (invalid values)
System.out.println(isValidIpv4("192.168.1")); // false (incomplete)
String networkLog = "Client 192.168.1.5 connected to server 10.0.0.1 via gateway 192.168.1.1";
System.out.println(extractIpv4Addresses(networkLog));
// [192.168.1.5, 10.0.0.1, 192.168.1.1]
}
}
Password Strength Checker
Validate password strength - minimum 8 characters, including uppercase, lowercase, numbers, and special characters.
// Combined password strength pattern
const strongPasswordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
// Function to check if password is strong
function isStrongPassword(password) {
return strongPasswordRegex.test(password);
}
// Function to get detailed password strength
function getPasswordStrength(password) {
const checks = {
length: password.length >= 8,
lowercase: /[a-z]/.test(password),
uppercase: /[A-Z]/.test(password),
number: /\d/.test(password),
special: /[@$!%*?&]/.test(password)
};
// Count passed checks
const passedChecks = Object.values(checks).filter(Boolean).length;
// Return strength level and details
return {
strength: passedChecks / 5, // 0 to 1 scale
isStrong: passedChecks === 5,
details: checks
};
}
// Examples
console.log(isStrongPassword("Weak123")); // false (no special char)
console.log(isStrongPassword("Strong123!")); // true
const password1 = "password";
const password2 = "Password1";
const password3 = "Password1!";
console.log(getPasswordStrength(password1));
// { strength: 0.4, isStrong: false, details: { ... } }
console.log(getPasswordStrength(password2));
// { strength: 0.8, isStrong: false, details: { ... } }
console.log(getPasswordStrength(password3));
// { strength: 1, isStrong: true, details: { ... } }
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
public class PasswordStrengthChecker {
// Patterns for different criteria
private static final Pattern HAS_LOWERCASE = Pattern.compile("[a-z]");
private static final Pattern HAS_UPPERCASE = Pattern.compile("[A-Z]");
private static final Pattern HAS_DIGIT = Pattern.compile("\\d");
private static final Pattern HAS_SPECIAL = Pattern.compile("[@$!%*?&]");
// Combined strong password pattern
private static final Pattern STRONG_PASSWORD =
Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$");
// Check if password is strong
public static boolean isStrongPassword(String password) {
return STRONG_PASSWORD.matcher(password).matches();
}
// Get detailed password strength
public static Map getPasswordStrength(String password) {
Map checks = new HashMap<>();
checks.put("length", password.length() >= 8);
checks.put("lowercase", HAS_LOWERCASE.matcher(password).find());
checks.put("uppercase", HAS_UPPERCASE.matcher(password).find());
checks.put("number", HAS_DIGIT.matcher(password).find());
checks.put("special", HAS_SPECIAL.matcher(password).find());
// Count passed checks
long passedChecks = checks.values().stream().filter(Boolean::booleanValue).count();
// Create result map
Map result = new HashMap<>();
result.put("strength", (double) passedChecks / 5); // 0 to 1 scale
result.put("isStrong", passedChecks == 5);
result.put("details", checks);
return result;
}
public static void main(String[] args) {
System.out.println(isStrongPassword("Weak123")); // false (no special char)
System.out.println(isStrongPassword("Strong123!")); // true
String password1 = "password";
String password2 = "Password1";
String password3 = "Password1!";
System.out.println(getPasswordStrength(password1));
// {strength=0.4, details={...}, isStrong=false}
System.out.println(getPasswordStrength(password2));
// {strength=0.8, details={...}, isStrong=false}
System.out.println(getPasswordStrength(password3));
// {strength=1.0, details={...}, isStrong=true}
}
}
Word Boundary Matching
Extract complete words from text using word boundaries (\b).
// Extract all words
function extractWords(text) {
return text.match(/\b\w+\b/g) || [];
}
// Find words that match a specific pattern
function findWords(text, pattern) {
const wordPattern = new RegExp(`\\b${pattern}\\b`, 'g');
return text.match(wordPattern) || [];
}
// Find words with a minimum length
function findLongWords(text, minLength) {
const longWordPattern = new RegExp(`\\b\\w{${minLength},}\\b`, 'g');
return text.match(longWordPattern) || [];
}
// Examples
const text = "Hello world! This is a sample text with some long and short words.";
console.log(extractWords(text));
// ["Hello", "world", "This", "is", "a", "sample", "text", "with", "some", "long", "and", "short", "words"]
console.log(findWords(text, "world|text|sample"));
// ["world", "sample", "text"]
console.log(findLongWords(text, 5));
// ["Hello", "world", "sample", "short", "words"]
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordBoundaryMatcher {
// Extract all words
public static List extractWords(String text) {
List words = new ArrayList<>();
Pattern pattern = Pattern.compile("\\b\\w+\\b");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
words.add(matcher.group());
}
return words;
}
// Find words that match a specific pattern
public static List findWords(String text, String wordPattern) {
List matchedWords = new ArrayList<>();
Pattern pattern = Pattern.compile("\\b(" + wordPattern + ")\\b");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
matchedWords.add(matcher.group());
}
return matchedWords;
}
// Find words with a minimum length
public static List findLongWords(String text, int minLength) {
List longWords = new ArrayList<>();
Pattern pattern = Pattern.compile("\\b\\w{" + minLength + ",}\\b");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
longWords.add(matcher.group());
}
return longWords;
}
public static void main(String[] args) {
String text = "Hello world! This is a sample text with some long and short words.";
System.out.println(extractWords(text));
// [Hello, world, This, is, a, sample, text, with, some, long, and, short, words]
System.out.println(findWords(text, "world|text|sample"));
// [world, sample, text]
System.out.println(findLongWords(text, 5));
// [Hello, world, sample, short, words]
}
}