πŸ” Regex Pattern Library

Updated: 2026-07-11

πŸ§ͺ Live Testing

Regex Pattern

Test Text

Match Results

Results will appear here...

πŸ“‹ Common Regex Patterns

How to Use

This regex pattern library is an essential tool for developers in daily work. It is simple to operate and fully featured. Here is the detailed usage guide:

Browse Patterns: The left sidebar category navigation lists 13 common categories. Click any category to filter the corresponding regex patterns. You can also enter keywords (such as "email", "phone") in the top search box, and the system will match and display relevant patterns in real time. All patterns have been practically verified and can be used directly in production environments.

Copy Patterns: Each pattern card contains a Copy Regex button. Click it to copy the regex to your clipboard, and a success notification will appear at the bottom of the page. You can also click the regex display area directly to manually copy it.

Live Testing: In the Live Testing section, enter or paste your regex in the Pattern box, enter your test text in the Test Text box, then click the Test Match button. The system will display all matching results in real time, including match positions, matched content, and captured group information. Click the Replace button to replace matched content with your specified string.

Quick Test: Click the Test This Pattern button on any template card, and the system will automatically fill that regex into the testing area for quick verification.

Use Cases

Regular expressions are widely used in software development and data processing. Here are some typical use cases:

Form Validation: In web development, both frontend and backend need to validate user input format. The email, phone, and ID regex patterns provided by this tool can be directly integrated into your projects to ensure user-submitted data meets expected formats, effectively preventing spam data and SQL injection attacks.

Log Analysis & Data Extraction: DevOps engineers and developers often need to extract key information from large volumes of logs. Using the date-time, IP address, and URL regex patterns from this tool, you can quickly extract access times, client IPs, and request paths from log files, significantly improving log analysis efficiency.

Data Cleaning & Formatting: Data analysts frequently need to clean non-compliant data items when processing raw data. For example, use the whitespace regex to remove extra spaces, the HTML tag regex to filter dangerous tags from rich text, and the special character regex to unify encoding formats.

Extended Knowledge

Basic Regex Syntax: . matches any character (except newline), ^ matches string start, $ matches string end, * matches 0 or more times, + matches 1 or more times, ? matches 0 or 1 time, {n,m} matches n to m times. [abc] matches any character in brackets, [^abc] matches any character not in brackets, \\d matches digits, \\w matches word characters, \\s matches whitespace.

Common Flags: g (global) match globally, i (ignoreCase) case-insensitive, m (multiline) multiline mode, s (dotAll) dot matches newlines, u (unicode) supports Unicode properties. For example /pattern/gi means global, case-insensitive matching.

Performance Tips: Complex regex patterns can cause performance issues, especially when processing long texts. Avoid nested quantifiers (like (a+)*) and patterns with heavy backtracking. For large log files, it is recommended to process in segments before applying regex matching. In JavaScript, pre-compiling regex patterns (defining regex literals outside loops) can significantly improve execution efficiency.

What is a regular expression?

A regular expression (Regex or RegEx) is a sequence of characters that defines a search pattern. It consists of normal characters and special meta-characters, used for text search, match, replace and validation operations. Widely used in form validation, log analysis, data extraction and more.

How many regex patterns does this library include?

This library includes over 100 commonly used regular expression patterns covering 13 categories: email validation, phone number validation, ID card validation, URL validation, IP address validation, number validation, date and time, postal codes, username and password, bank cards, license plates, HTML/XML tags, and general text processing.

How do I use the live testing feature?

In the Live Testing section on the right side, paste your test text into the Test Text box, then enter or paste your regex pattern into the Pattern box and click Test Match. The system will display all matching results including positions, matched content and captured groups in real time. You can also click the Test This Pattern button on any template card to auto-fill the pattern into the testing area.

Is regex a programming language?

No. Regular expressions are a pattern description language. Almost all mainstream programming languages have built-in regex support, including JavaScript, Python, Java, PHP, Go, C# and more. The regex syntax is basically consistent across languages, but there may be slight differences in advanced features such as named capture groups and Unicode properties.

Why does my regex pattern not match?

Common reasons include: (1) forgetting to add escape characters, e.g. ., * and other meta-characters need to be escaped as \\., \\*; (2) incorrect flag settings, add i flag if you need case-insensitive matching; (3) hidden characters in the string, use the testing tool to confirm the raw text content first; (4) using advanced syntax not supported by a specific language.

Can regex handle Unicode?

Yes. Modern JavaScript supports Unicode property escapes, such as \\p{L} matching any letter (including Chinese), \\p{N} matching any digit, \\p{Han} matching Chinese characters. Use the u flag, for example /\\p{Han}+/gu.

Can these regex patterns be used in production directly?

Most patterns have been practically verified and can be used directly. However, it is recommended to thoroughly test with your actual data before integrating into your project. For complex scenarios like email validation, regex only provides format-level preliminary validation, and complete verification requires additional methods such as SMTP verification.

How do I learn regular expressions?

Start with the basic syntax: first master the meaning of core meta-characters like ., *, +, ?, [], (), |, then practice with real cases. This tool provides rich common templates that can serve as learning references. Start with simple email matching and gradually master advanced features like group capturing and lookahead assertions.

Regex Pattern Library Β· 100+ Ready-to-Use Patterns Β· Pure Client-Side Β· Data Never Leaves Your Browser

One-Click Copy Β· Live Testing Β· Real-Time Matching

Feedback: dexshuang@google.com

const PATTERNS = [ {cat:'email', name:'Standard Email', regex:'^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$', desc:'Matches most common email address formats including username, @ symbol and domain', flags:'i'}, {cat:'email', name:'Strict Email (RFC 5322)', regex:'^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$', desc:'RFC 5322 compliant strict email validation, supports subdomains and special characters', flags:'i'}, {cat:'email', name:'Gmail Address', regex:'^[a-zA-Z0-9._%+-]{1,64}@gmail\\.com$', desc:'Matches Gmail addresses with valid username format', flags:'i'}, {cat:'email', name:'Outlook/Hotmail', regex:'^[a-zA-Z0-9._%+-]{1,64}@(outlook|hotmail|live)\\.com$', desc:'Matches Outlook/Hotmail/Live email addresses', flags:'i'}, {cat:'email', name:'Company Email', regex:'^[\\w.-]+@([\\w-]+\\.)+[a-zA-Z]{2}$', desc:'Generic company email format, works for most business emails', flags:'i'}, {cat:'phone', name:'US Phone Number', regex:'^(\\+1[-\\s]?)?\\(?([0-9]{3})\\)?[-\\s]?([0-9]{3})[-\\s]?([0-9]{4})$', desc:'Matches US phone numbers with optional area code and country code', flags:''}, {cat:'phone', name:'UK Phone Number', regex:'^(\\+44|0)7\\d{9}$', desc:'Matches UK mobile numbers starting with 07 or +447', flags:''}, {cat:'phone', name:'International Format', regex:'^\\+[1-9]\\d{1,14}$', desc:'Matches international phone numbers in E.164 format (+ followed by 1-15 digits)', flags:''}, {cat:'phone', name:'Phone with Extension', regex:'^(\\+?\\d{1,3}[-\\s]?)?\\(?\\d{3}\\)?[-\\s]?\\d{3}[-\\s]?\\d{4}(\\s?(ext|x)\\.?\\s?\\d{1,5})?$', desc:'Matches phone numbers with optional extension', flags:'i'}, {cat:'url', name:'Standard URL', regex:'^https?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$', desc:'Matches HTTP/HTTPS protocol URLs', flags:'i'}, {cat:'url', name:'Full URL (with params)', regex:'^(https?|ftp)://(\\S+\\.)+\\S{2}(/[\\S]*)?$', desc:'Matches complete URLs including query parameters, supports ftp protocol', flags:'i'}, {cat:'url', name:'IPv4 Address', regex:'^(?:(?: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]?)$', desc:'Strictly matches IPv4 addresses, each octet between 0-255', flags:''}, {cat:'url', name:'IPv6 Address', regex:'^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$', desc:'Matches standard IPv6 address formats', flags:'i'}, {cat:'url', name:'Domain Name', regex:'^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2}$', desc:'Matches domain names, supports multi-level subdomains', flags:'i'}, {cat:'url', name:'MAC Address', regex:'^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$', desc:'Matches standard MAC address format with colon or hyphen separators', flags:'i'}, {cat:'idcard', name:'US Social Security Number', regex:'^(?!000|666|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0000)\\d{4}$', desc:'Matches US SSN format XXX-XX-XXXX with validation rules', flags:''}, {cat:'idcard', name:'UK National Insurance', regex:'^(?!BG|GB|NK|KN|TN|NT|ZZ)[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\\d{6}[A-D]$', desc:'Matches UK National Insurance number format', flags:'i'}, {cat:'idcard', name:'Passport Number (Generic)', regex:'^[A-Z0-9]{6,9}$', desc:'Generic passport number format, 6-9 alphanumeric characters', flags:'i'}, {cat:'number', name:'Integer', regex:'^-?\\d+$', desc:'Matches positive and negative integers without decimal points', flags:''}, {cat:'number', name:'Positive Integer', regex:'^\\d+$', desc:'Matches non-negative integers (0 and positive)', flags:''}, {cat:'number', name:'Decimal Number', regex:'^-?\\d+(\\.\\d+)?$', desc:'Matches positive and negative decimal numbers including integers', flags:''}, {cat:'number', name:'Positive Decimal', regex:'^\\d+(\\.\\d+)?$', desc:'Matches non-negative decimal numbers', flags:''}, {cat:'number', name:'Scientific Notation', regex:'^-?\\d+(\\.\\d+)?[eE][+-]?\\d+$', desc:'Matches numbers in scientific notation, e.g. 1.23e10', flags:''}, {cat:'number', name:'Percentage', regex:'^(\\d{1,3}|\\d{1,3}(\\.\\d+)?)%$', desc:'Matches percentage format like 50%, 99.5%', flags:''}, {cat:'number', name:'Currency Amount', regex:'^\\d+(,\\d{3})*(\\.\\d{1,2})?$', desc:'Matches currency amounts with thousands separators, up to 2 decimal places', flags:''}, {cat:'number', name:'Hex Color', regex:'^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$', desc:'Matches CSS hex color values, supports 3 and 6 digit shorthand', flags:'i'}, {cat:'number', name:'RGB Color', regex:'^rgb\\s*\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*\\)$', desc:'Matches CSS RGB color values', flags:'i'}, {cat:'date', name:'Date YYYY-MM-DD', regex:'^(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\\d|3[0-1])$', desc:'Matches YYYY-MM-DD format dates', flags:''}, {cat:'date', name:'Date MM/DD/YYYY', regex:'^(0[1-9]|1[0-2])/(0[1-9]|[1-2]\\d|3[0-1])/(\\d{4})$', desc:'Matches MM/DD/YYYY format dates (US format)', flags:''}, {cat:'date', name:'Date DD-MM-YYYY', regex:'^(0[1-9]|[1-2]\\d|3[0-1])-(0[1-9]|1[0-2])-(\\d{4})$', desc:'Matches DD-MM-YYYY format dates', flags:''}, {cat:'date', name:'Time HH:MM:SS', regex:'^([01]\\d|2[0-3]):([0-5]\\d):([0-5]\\d)$', desc:'Matches 24-hour time format', flags:''}, {cat:'date', name:'DateTime ISO 8601', regex:'^(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\\d|3[0-1])T([01]\\d|2[0-3]):([0-5]\\d):([0-5]\\d)(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})?$', desc:'Matches ISO 8601 standard datetime format', flags:''}, {cat:'date', name:'Date with Month Name', regex:'^(\\d{1,2})\\s+(January|February|March|April|May|June|July|August|September|October|November|December)\\s+(\\d{4})$', desc:'Matches date with full month name, e.g. 15 January 2024', flags:'i'}, {cat:'text', name:'English Letters Only', regex:'^[a-zA-Z]+$', desc:'Matches strings containing only English letters', flags:''}, {cat:'text', name:'Alphanumeric', regex:'^[a-zA-Z0-9]+$', desc:'Matches strings containing only letters and digits', flags:''}, {cat:'text', name:'Whitespace Line', regex:'^\\s*$', desc:'Matches lines containing only whitespace characters', flags:'m'}, {cat:'text', name:'Consecutive Spaces', regex:' {2}', desc:'Matches 2 or more consecutive spaces', flags:'g'}, {cat:'text', name:'HTML Comments', regex:'', desc:'Matches HTML/XML comment content', flags:'g'}, {cat:'text', name:'Multi-line Comment Block', regex:'/\\*[\\s\\S]*?\\*/', desc:'Matches C/Java/JavaScript style multi-line comments', flags:'g'}, {cat:'text', name:'Single-line Comment', regex:'//.*$', desc:'Matches C/Java/JavaScript style single-line comments', flags:'gm'}, {cat:'text', name:'Windows Path', regex:'^[a-zA-Z]:\\\\([\\w\\s-]+\\\\?)*$', desc:'Matches Windows file path format', flags:''}, {cat:'text', name:'Unix Path', regex:'^(/[\\w.-]+)+/?$', desc:'Matches Unix/Linux file path format', flags:''}, {cat:'password', name:'Strong Password (8+ chars, mixed case, digits, symbols)', regex:'^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8}$', desc:'Password at least 8 characters with uppercase, lowercase, digits and special symbols', flags:''}, {cat:'password', name:'Medium Password (6+ chars, letters + digits)', regex:'^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6}$', desc:'Password at least 6 characters with letters and digits', flags:''}, {cat:'password', name:'Username (letters, digits, underscore)', regex:'^[a-zA-Z0-9_]{4,16}$', desc:'Username 4-16 characters, letters, digits and underscores only', flags:''}, {cat:'password', name:'US ZIP Code', regex:'^\\d{5}(-\\d{4})?$', desc:'Matches US ZIP codes with optional +4 extension', flags:''}, {cat:'password', name:'UK Postcode', regex:'^[A-Z]{1,2}[0-9][A-Z0-9]?\\s?[0-9][A-Z]{2}$', desc:'Matches UK postcode format', flags:'i'}, {cat:'password', name:'Canadian Postal Code', regex:'^[A-Za-z]\\d[A-Za-z][\\s-]?\\d[A-Za-z]\\d$', desc:'Matches Canadian postal code format A1A 1A1', flags:'i'}, {cat:'finance', name:'Credit Card (Visa/MC/Amex/Discover)', regex:'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|3[0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})$', desc:'Matches Visa, MasterCard, American Express, Discover and DinersClub formats', flags:''}, {cat:'finance', name:'IBAN', regex:'^[A-Z]{2}[0-9]{2}[A-Z0-9]{4}[0-9]{7}([A-Z0-9]?){0,16}$', desc:'Matches International Bank Account Number format', flags:'i'}, {cat:'finance', name:'US License Plate', regex:'^[A-Z0-9]{3,8}$', desc:'Matches US license plate format (varies by state)', flags:'i'}, {cat:'finance', name:'ISBN-13', regex:'^978[0-9]{10}$|^979[0-9]{10}$', desc:'Matches ISBN-13 book numbers starting with 978 or 979', flags:''}, {cat:'finance', name:'ISBN-10', regex:'^[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$', desc:'Matches ISBN-10 book number format', flags:'i'}, {cat:'html', name:'HTML Tag', regex:'<\\w+[^>]*>', desc:'Matches HTML opening tags', flags:'g'}, {cat:'html', name:'HTML Tag (with closing)', regex:'<\\/?\\w+[^>]*>', desc:'Matches HTML opening and closing tags', flags:'g'}, {cat:'html', name:'HTML Attributes', regex:'\\s[a-zA-Z-]+=["\'][^"\']*["\']', desc:'Matches HTML tag attribute key-value pairs', flags:'g'}, {cat:'html', name:'XML Tag', regex:'<[\\w:]+[^>]*>', desc:'Matches XML tags including namespace', flags:'g'}, {cat:'html', name:'HTML Entity', regex:'&[a-zA-Z0-9#]+;', desc:'Matches HTML entity encodings', flags:'g'}, {cat:'html', name:'Markdown Link', regex:'\\[[^\\]]+\\]\\([^\\)]+\\)', desc:'Matches Markdown link format [text](url)', flags:'g'}, {cat:'programming', name:'UUID v4', regex:'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', desc:'Matches UUID v4 format', flags:'i'}, {cat:'programming', name:'UUID Generic', regex:'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$', desc:'Matches generic UUID format (any version)', flags:'i'}, {cat:'programming', name:'Git Commit Hash', regex:'^[a-f0-9]{40}$', desc:'Matches Git full commit hash (40 hex characters)', flags:'i'}, {cat:'programming', name:'Git Short Hash', regex:'^[a-f0-9]{7,8}$', desc:'Matches Git short commit hash (7-8 hex characters)', flags:'i'}, {cat:'programming', name:'Hexadecimal String', regex:'^[0-9a-fA-F]+$', desc:'Matches pure hexadecimal character sequence', flags:''}, {cat:'programming', name:'Base64 String', regex:'^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$', desc:'Matches Base64 encoded string', flags:''}, {cat:'programming', name:'SQL Injection Pattern', regex:'(\\b(union|select|insert|update|delete|drop|create|alter|exec|execute)\\b|\\b(or|and)\\b\\s*\\d*\\s*=\\s*\\d*)', desc:'Detects SQL injection attack signature strings', flags:'i'}, {cat:'other', name:'Emoji', regex:'[\\x{1F600}-\\x{1F64F}\\x{1F300}-\\x{1F5FF}\\x{1F680}-\\x{1F6FF}\\x{1F1E0}-\\x{1F1FF}\\x{2600}-\\x{26FF}\\x{2700}-\\x{27BF}]', desc:'Matches common Emoji characters', flags:'u'}, {cat:'other', name:'Social Media Handle', regex:'^@[a-zA-Z0-9_]{1,15}$', desc:'Matches Twitter/X/Instagram handle format (@ prefix)', flags:''}, {cat:'other', name:'File Extension', regex:'\\.(jpg|jpeg|png|gif|bmp|webp|svg|pdf|doc|docx|xls|xlsx|ppt|pptx|txt|zip|rar|7z)$', desc:'Matches common file extensions', flags:'i'}, {cat:'other', name:'Base64 Image DataURI', regex:'^data:image\\/(png|jpeg|jpg|gif|webp|svg\\+xml);base64,[A-Za-z0-9+/]+=*$', desc:'Matches Base64 encoded image DataURI', flags:'i'}, {cat:'other', name:'CSS Class Name', regex:'^[a-zA-Z_-][a-zA-Z0-9_-]*$', desc:'Matches valid CSS class names', flags:''}, {cat:'other', name:'URL Slug', regex:'^[a-z0-9]+(?:-[a-z0-9]+)*$', desc:'Matches URL-friendly slug format strings', flags:''}, {cat:'other', name:'YouTube Video ID', regex:'^[a-zA-Z0-9_-]{11}$', desc:'Matches YouTube video ID (11 characters)', flags:''} ]; const CAT_NAMES = { all:'All Patterns', email:'Email Validation', phone:'Phone Numbers', url:'URL/IP Validation', idcard:'ID Validation', number:'Number Validation', date:'Date & Time', text:'Text Processing', password:'Username & Password', finance:'Bank Card / License', html:'HTML/XML', programming:'Programming', other:'Others' }; let currentCat = 'all'; function filterCat(cat) { currentCat = cat; document.querySelectorAll('.cat-list a').forEach(a => a.classList.remove('active')); const target = document.querySelector('.cat-list a[href="#'+cat+'"]'); if(target) target.classList.add('active'); renderPatterns(); } function renderPatterns() { const list = document.getElementById('patternList'); const search = (document.getElementById('searchBox').value || '').toLowerCase(); let filtered = PATTERNS; if(currentCat !== 'all') { filtered = filtered.filter(p => p.cat === currentCat); } if(search) { filtered = filtered.filter(p => p.name.toLowerCase().includes(search) || p.regex.includes(search) || p.desc.toLowerCase().includes(search)); } list.innerHTML = ''; let currentCatName = ''; filtered.forEach(function(p, idx) { const catName = CAT_NAMES[p.cat]; if(catName !== currentCatName && currentCat === 'all') { currentCatName = catName; const sec = document.createElement('div'); sec.innerHTML = '

'+catName+'

'; list.appendChild(sec); } const card = document.createElement('div'); card.className = 'pattern-card'; card.innerHTML = '

'+p.name+'

'+ '
'+escapeHTML(p.regex)+'
'+ '
'+p.desc+'
'+ '
'+(p.flags ? 'Flags: '+p.flags+'' : '')+''+filtered.length+' templates
'+ '
'+ ''+ ''+ '
'; list.appendChild(card); }); if(filtered.length === 0) { list.innerHTML = '

No matching regex patterns found

'; } } function escapeHTML(s) { return s.replace(/&/g,'&').replace(//g,'>'); } function escapeJS(s) { return s.replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/\n/g,'\\n'); } function showToast(msg) { const toast = document.getElementById('toast'); toast.textContent = msg; toast.classList.add('show'); setTimeout(function(){ toast.classList.remove('show'); }, 2000); } function copyRegex(regex) { navigator.clipboard.writeText(regex).then(function(){ showToast('βœ… Regex copied to clipboard'); }) .catch(function(){ showToast('❌ Copy failed, please copy manually'); }); } function testPattern(regex, flags) { document.getElementById('testPattern').value = '/' + regex + '/' + flags; showToast('Pattern filled in testing area'); document.getElementById('testPattern').scrollIntoView({behavior:'smooth', block:'center'}); } function runTest() { const patternInput = document.getElementById('testPattern').value.trim(); const text = document.getElementById('testText').value; const resultEl = document.getElementById('testResult'); if(!patternInput) { resultEl.textContent = 'Please enter a regex pattern'; return; } if(!text) { resultEl.textContent = 'Please enter test text'; return; } let regex, flags = '', pattern = patternInput; const slashMatch = patternInput.match(/^\/(.+)\/([gimuyus]*)$/); if(slashMatch) { pattern = slashMatch[1]; flags = slashMatch[2]; } else if(patternInput.startsWith('/') && patternInput.endsWith('/')) { pattern = patternInput.slice(1,-1); } try { regex = new RegExp(pattern, flags || 'g'); } catch(e) { resultEl.innerHTML = 'Regex syntax error: '+escapeHTML(e.message)+''; return; } let matches = []; let match; const globalRegex = regex.global ? regex : new RegExp(regex.source, regex.flags + 'g'); let count = 0; while((match = globalRegex.exec(text)) !== null && count < 100) { count++; matches.push({ text: match[0], index: match.index, groups: match.slice(1).filter(function(g){ return g !== undefined; }) }); if(match[0] === '') globalRegex.lastIndex++; } if(matches.length === 0) { resultEl.innerHTML = 'No matches found'; return; } let html = '
βœ… Found '+matches.length+' match'+(matches.length>1?'es':'')+'
'; matches.forEach(function(m, i) { html += '
'; html += 'Match #'+(i+1)+': Position '+m.index+'
'; html += ''+escapeHTML(m.text)+''; if(m.groups.length > 0) { html += '
Captured groups: '; m.groups.forEach(function(g, gi) { html += '['+(gi+1)+'] '+escapeHTML(g)+' '; }); } html += '
'; }); resultEl.innerHTML = html; } function runReplace() { const patternInput = document.getElementById('testPattern').value.trim(); const text = document.getElementById('testText').value; const resultEl = document.getElementById('testResult'); if(!patternInput) { resultEl.textContent = 'Please enter a regex pattern'; return; } if(!text) { resultEl.textContent = 'Please enter test text'; return; } let flags = '', pattern = patternInput; const slashMatch = patternInput.match(/^\/(.+)\/([gimuyus]*)$/); if(slashMatch) { pattern = slashMatch[1]; flags = slashMatch[2]; } else if(patternInput.startsWith('/') && patternInput.endsWith('/')) { pattern = patternInput.slice(1,-1); } try { const regex = new RegExp(pattern, flags || 'g'); const replacement = prompt('Enter replacement string (supports $1 $2 group references):', ''); if(replacement === null) return; const result = text.replace(regex, replacement); resultEl.innerHTML = '
βœ… Replacement complete
'+escapeHTML(result)+'
'; } catch(e) { resultEl.innerHTML = 'Replace error: '+escapeHTML(e.message)+''; } } function clearTest() { document.getElementById('testPattern').value = ''; document.getElementById('testText').value = ''; document.getElementById('testResult').textContent = 'Results will appear here...'; } document.getElementById('searchBox').addEventListener('input', renderPatterns); renderPatterns();