Java and JavaScript Regular Expression Samples

Practical regex examples for programmers

Table of Contents

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 태그 제거

텍스트에서 HTML 태그를 제거하는 정규 표현식.


// 간단한 HTML 태그 제거
function stripHtmlTags(html) {
    return html.replace(/<[^>]*>/g, '');
}

// HTML 태그 제거 및 엔티티 처리
function stripHtmlTagsAndEntities(html) {
    // 먼저 일반적인 HTML 엔티티 치환
    const withoutEntities = html
        .replace(/ /g, ' ')
        .replace(/&/g, '&')
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/"/g, '"')
        .replace(/'/g, "'");
    
    // 그 다음 모든 HTML 태그 제거
    return withoutEntities.replace(/<[^>]*>/g, '');
}

// 예제
const htmlContent = "

이것은 굵은 그리고 이탤릭 텍스트와 링크입니다.

"; console.log(stripHtmlTags(htmlContent)); // "이것은 굵은 그리고 이탤릭 텍스트와 링크입니다." const htmlWithEntities = "

이것 & 저것 "따옴표"와 <태그>.

"; console.log(stripHtmlTagsAndEntities(htmlWithEntities)); // "이것 & 저것 "따옴표"와 <태그>."

public class HtmlTagRemover {
    // 간단한 HTML 태그 제거
    public static String stripHtmlTags(String html) {
        return html.replaceAll("<[^>]*>", "");
    }
    
    // HTML 태그 제거 및 엔티티 처리
    public static String stripHtmlTagsAndEntities(String html) {
        // 먼저 일반적인 HTML 엔티티 치환
        String withoutEntities = html
            .replaceAll(" ", " ")
            .replaceAll("&", "&")
            .replaceAll("<", "<")
            .replaceAll(">", ">")
            .replaceAll(""", "\"")
            .replaceAll("'", "'");
        
        // 그 다음 모든 HTML 태그 제거
        return withoutEntities.replaceAll("<[^>]*>", "");
    }
    
    public static void main(String[] args) {
        String htmlContent = "

이것은 굵은 그리고 이탤릭 텍스트와 링크입니다.

"; System.out.println(stripHtmlTags(htmlContent)); // "이것은 굵은 그리고 이탤릭 텍스트와 링크입니다." String htmlWithEntities = "

이것 & 저것 "따옴표"와 <태그>.

"; System.out.println(stripHtmlTagsAndEntities(htmlWithEntities)); // "이것 & 저것 "따옴표"와 <태그>." } }

IP 주소(IPv4) 검증

IPv4 주소를 검증하고 추출합니다.


// IPv4 주소 패턴
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/;

// IPv4 주소 검증 함수
function isValidIpv4(ip) {
    return ipv4Regex.test(ip);
}

// 텍스트에서 IPv4 주소 추출 함수
function extractIpv4Addresses(text) {
    const ipRegex = new RegExp(ipv4Regex.source, 'g');
    return text.match(ipRegex) || [];
}

// 예제
console.log(isValidIpv4("192.168.1.1")); // true
console.log(isValidIpv4("255.255.255.255")); // true
console.log(isValidIpv4("256.256.256.256")); // false (유효하지 않은 값)
console.log(isValidIpv4("192.168.1")); // false (불완전)

const networkLog = "클라이언트 192.168.1.5가 게이트웨이 192.168.1.1을 통해 서버 10.0.0.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 주소 패턴
    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);
    
    // IPv4 주소 검증
    public static boolean isValidIpv4(String ip) {
        return IPV4_REGEX.matcher(ip).matches();
    }
    
    // 텍스트에서 IPv4 주소 추출
    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 (유효하지 않은 값)
        System.out.println(isValidIpv4("192.168.1")); // false (불완전)
        
        String networkLog = "클라이언트 192.168.1.5가 게이트웨이 192.168.1.1을 통해 서버 10.0.0.1에 연결되었습니다";
        System.out.println(extractIpv4Addresses(networkLog));
        // [192.168.1.5, 10.0.0.1, 192.168.1.1]
    }
}
                    

비밀번호 강도 검사기

비밀번호 강도 검증 - 최소 8자, 대문자, 소문자, 숫자, 특수 문자 포함.


// 통합 비밀번호 강도 패턴
const strongPasswordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;

// 비밀번호가 강력한지 확인하는 함수
function isStrongPassword(password) {
    return strongPasswordRegex.test(password);
}

// 비밀번호 강도 상세 정보 확인 함수
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)
    };
    
    // 통과된 검사 개수
    const passedChecks = Object.values(checks).filter(Boolean).length;
    
    // 강도 레벨과 상세 정보 반환
    return {
        strength: passedChecks / 5, // 0에서 1 사이 점수
        isStrong: passedChecks === 5,
        details: checks
    };
}

// 예제
console.log(isStrongPassword("Weak123")); // false (특수 문자 없음)
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 (특수 문자 없음)
        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}
    }
}
                    

단어 경계 매칭

단어 경계(\b)를 사용하여 텍스트에서 완전한 단어를 추출합니다.


// 모든 단어 추출
function extractWords(text) {
    return text.match(/\b\w+\b/g) || [];
}

// 특정 패턴과 일치하는 단어 찾기
function findWords(text, pattern) {
    const wordPattern = new RegExp(`\\b${pattern}\\b`, 'g');
    return text.match(wordPattern) || [];
}

// 최소 길이를 가진 단어 찾기
function findLongWords(text, minLength) {
    const longWordPattern = new RegExp(`\\b\\w{${minLength},}\\b`, 'g');
    return text.match(longWordPattern) || [];
}

// 예제
const text = "안녕 세계! 이것은 몇 가지 길고 짧은 단어가 포함된 샘플 텍스트입니다.";

console.log(extractWords(text));
// ["안녕", "세계", "이것은", "몇", "가지", "길고", "짧은", "단어가", "포함된", "샘플", "텍스트입니다"]

console.log(findWords(text, "세계|텍스트|샘플"));
// ["세계", "샘플", "텍스트"]

console.log(findLongWords(text, 3));
// ["안녕", "세계", "이것은", "가지", "길고", "짧은", "단어가", "포함된", "샘플", "텍스트입니다"]
                    

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

public class WordBoundaryMatcher {
    // 모든 단어 추출
    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;
    }
    
    // 특정 패턴과 일치하는 단어 찾기
    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;
    }
    
    // 최소 길이를 가진 단어 찾기
    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 = "안녕 세계! 이것은 몇 가지 길고 짧은 단어가 포함된 샘플 텍스트입니다.";
        
        System.out.println(extractWords(text));
        // [안녕, 세계, 이것은, 몇, 가지, 길고, 짧은, 단어가, 포함된, 샘플, 텍스트입니다]
        
        System.out.println(findWords(text, "세계|텍스트|샘플"));
        // [세계, 샘플, 텍스트]
        
        System.out.println(findLongWords(text, 3));
        // [안녕, 세계, 이것은, 가지, 길고, 짧은, 단어가, 포함된, 샘플, 텍스트입니다]
    }
}