Frequently asked.
What is regexguide.com?
A free, in-browser regex explainer and pattern library. Paste any regex, get a plain-English breakdown. No signup, no upload, no tracking of your regex content.
100+ regex questions, answered.
A hand-written answer to the questions people search for most — the syntax, the validation patterns, and the language-specific how-tos. Each answer links to our explainer or a tested pattern where one exists.
Regex basics
What is a regular expression (regex)?
A regular expression is a compact string of symbols that describes a search pattern. Instead of matching one fixed word, a regex can match a whole family of strings — for example \d{3}-\d{4} matches any seven-digit, phone-style number. Regex engines are built into almost every programming language and text editor and are used to search, validate, extract, and replace text. Paste any pattern into our explainer for a plain-English breakdown.
How to test a regex pattern online?
Paste your pattern and a sample string into an online tester. Our explainer shows what each token means, while sites like regex101 focus on live match testing. Testing against your own real sample data is the only reliable way to confirm a pattern before you ship it.
How to escape special characters in regex?
Put a backslash before any metacharacter — . ^ $ * + ? ( ) [ ] { } | \ / — to match it literally. For example, a literal dot is \. and a literal opening paren is \(. To escape a dynamic string in JavaScript, use str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').
How to do a case-insensitive regex search?
Add the case-insensitive flag. In JavaScript that is the i flag — /hello/i matches "Hello", "HELLO", and "hello". In Python pass re.IGNORECASE, in most editors tick the "Aa" toggle, and in PCRE-style engines use the inline modifier (?i).
Metacharacters & character classes
What does \d mean in regex?
\d matches any single digit, 0–9 (in Unicode mode it can also match digits from other scripts). Its opposite, \D, matches any non-digit. So \d{4} matches exactly four digits, like a year.
What does \w match in regular expressions?
\w matches a single "word character": the letters A–Z and a–z, the digits 0–9, and the underscore _. \W is its inverse (any non-word character). Note that it does not include hyphens, spaces, or most punctuation.
What does \s mean in regex?
\s matches any whitespace character — a space, tab \t, newline \n, carriage return \r, form feed, or vertical tab. \S matches any non-whitespace character. Use \s+ to match a run of whitespace.
What does \b (word boundary) mean in regex?
\b is a zero-width word boundary — it matches the position between a word character (\w) and a non-word character, not an actual character. \bcat\b matches "cat" as a whole word but not the "cat" inside "category".
What does the dot . match in regex?
The dot . matches any single character except a line break. To also match newlines, enable the dotAll flag (s in JavaScript and PCRE) or use a class like [\s\S]. To match a literal period, escape it as \..
What does \A and \Z mean in regex flavors?
\A anchors to the very start of the input and \Z (or \z) to the very end, regardless of the multiline flag — unlike ^ and $, which can match at internal line breaks in multiline mode. They exist in Python, Java, PCRE, and Ruby, but not in JavaScript, which relies on ^/$ instead.
What is a character class [] in regex?
Square brackets define a character class — a set of characters, any one of which can match at that position. [aeiou] matches one vowel, [a-z] matches one lowercase letter via a range, and a leading caret negates the set, so [^0-9] matches any character that is not a digit.
How to match any character except newline?
Use the dot ., which matches any character except a line break by default. To match truly any character including newlines, use a class like [\s\S] or turn on the dotAll (s) flag.
How to match whitespace characters in regex?
Use \s for a single whitespace character or \s+ for one or more in a row. To match only spaces and tabs but not newlines, use an explicit class such as [ \t].
How to match alphanumeric characters only?
Use ^[A-Za-z0-9]+$ to match a string made up entirely of letters and digits. Add the underscore with ^\w+$, or allow Unicode letters with ^[\p{L}\p{N}]+$ and the u flag.
How to match numbers only using regex?
Use ^\d+$ to match a string of one or more digits and nothing else. For an optional sign and decimals, use ^-?\d+(\.\d+)?$.
Quantifiers & anchors
What do ^ and $ anchor tags do in regex?
^ anchors a match to the start of the string and $ to the end — both are zero-width, matching a position rather than a character. Wrapping a pattern in ^...$ forces it to match the entire string, which is essential for validation. With the multiline flag they anchor to the start and end of each line.
What is the difference between * and + quantifiers?
* means "zero or more" of the preceding token, so it can match nothing; + means "one or more", requiring at least one. For example a* matches the empty string, while a+ needs at least one "a". Add ? (as in a+?) to make either one lazy.
What is the difference between greedy and lazy matching?
By default quantifiers are greedy — they match as much as possible and then backtrack. Adding ? makes them lazy, matching as little as possible. On "<a><b>", <.*> grabs the whole string, but <.*?> stops at the first ">". A lazy quantifier is the usual fix for "my pattern matches too much".
How to match optional characters using regex?
Follow the optional part with ?, which means "zero or one". colou?r matches both "color" and "colour", and https? makes the "s" optional. Group several optional characters with parentheses, e.g. (ing)?.
How to match exactly N number of characters?
Use a fixed quantifier: \d{4} matches exactly four digits. {2,4} matches two to four, {3,} matches three or more, and {0,2} matches up to two.
How to match a range of numbers in regex?
Regex matches text, not numeric value, so you build a range digit by digit. For 0–255 (an IP octet) use 25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d. For a small fixed range a class works: [1-9]|1[0-2] matches 1–12.
Groups, lookaround & backreferences
What is a non-capturing group (?:)?
(?:...) groups part of a pattern — so you can apply a quantifier or alternation to it — without saving the match into a numbered capture group. Use it when you need grouping but not the captured text, which keeps your group numbers and backreferences clean: (?:ab)+ repeats "ab" without storing it.
What are named capturing groups in regex?
Name a group with (?<year>\d{4}) and refer to it by name instead of a number — far more readable in long patterns. Read it via match.groups.year in JavaScript or m.group('year') in Python; .NET uses the same (?<name>) syntax.
What is a backreference in regular expressions?
A backreference matches the same text a previous group captured. (\w+)\s+\1 finds a doubled word because \1 must equal whatever group 1 captured — ideal for spotting duplicate words. Named backreferences use \k<name>.
What is a regex lookahead assertion?
A lookahead (?=...) asserts that what follows matches, without consuming it. \d+(?= dollars) matches the number in "100 dollars" but not the word. Because lookaheads are zero-width, several are often stacked for password rules like "must contain a digit".
What is a regex lookbehind assertion?
A lookbehind (?<=...) asserts that what precedes the current position matches, without including it in the result. (?<=\$)\d+ matches the digits after a "$". Lookbehind is supported in modern JavaScript, Python, .NET, PCRE, and Java, though some older engines restrict it to fixed length.
How to use negative lookahead (?!)?
(?!...) asserts that what follows does NOT match. foo(?!bar) matches "foo" only when it is not followed by "bar". It is the standard way to exclude cases, e.g. ^(?!.*--).+$ rejects any string containing "--".
How to match multiple patterns using OR |?
The pipe | means "or", trying each alternative in turn: cat|dog|fish matches any one of the three. Wrap the alternatives in a group to limit their scope — ^(cat|dog)$ — otherwise the | splits the entire pattern in two.
How to match strings that do not start with a specific character?
Use a negative lookahead right after the start anchor: ^(?!#).* matches any line that does not begin with "#". To reject a whole starting word, use ^(?!error).*.
Flags & modes
What is the global flag (/g) in regex?
The global flag g makes a pattern find every match rather than stopping at the first. In JavaScript, str.match(/\d+/g) returns all numbers and a /g pattern in replace substitutes every occurrence. Without it, you only get the first match.
What is the multiline flag (/m) in regex?
The multiline flag m changes ^ and $ so they match at the start and end of each line, not only the whole string. It is essential when you process multi-line text line by line.
What is the dotAll flag (/s) in regex?
The dotAll flag s lets the dot . match newline characters too, so . matches literally any character. It is handy for capturing a block of text that spans several lines.
Validation patterns
How to validate email using regex?
A practical pattern is ^[^\s@]+@[^\s@]+\.[^\s@]+$ — some non-space, non-@ characters, an @, a domain, a dot, and a suffix. A fully RFC-5322-compliant email regex is enormous and rarely worth it: validate loosely, then confirm by sending a real message. See our tested email pattern.
Source: RFC 5322 — email addresses
How to write a regex for phone number validation?
Anchor to the specific format you accept — a flexible international check is ^\+?[1-9]\d{7,14}$ (E.164 style), while a US number is ^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$. Formats vary by country, so avoid one "global" pattern; see our US phone and E.164 patterns.
Source: ITU-T E.164 — phone numbering
How to write a strong password validation regex?
Stack a zero-width lookahead for each rule, then check the length: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$ requires a lowercase, an uppercase, a digit, a symbol, and 8+ characters. See the strong-password pattern.
How to validate IP addresses (IPv4/IPv6) with regex?
For IPv4, validate each octet as 0–255: ^((25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(25[0-5]|2[0-4]\d|1?\d?\d)$. IPv6 is considerably more complex; use our tested IPv4 and IPv6 patterns.
Source: RFC 791 — IPv4, RFC 4291 — IPv6
How to write a regex for date format validation?
Match the structure with regex, then validate real calendar dates in code — regex cannot easily reject "Feb 30". A basic ISO check is ^\d{4}-\d{2}-\d{2}$. See our ISO, US, and EU date patterns.
Source: ISO 8601 — date/time
How to match dates in YYYY-MM-DD format?
Use ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$ to enforce month 01–12 and day 01–31. This validates format and ranges; still reject impossible dates like 31 April in code. See the ISO-date pattern.
Source: ISO 8601 — date/time
How to validate a valid time in 24-hour format using regex?
Use ^([01]\d|2[0-3]):[0-5]\d$ for HH:MM in 24-hour time (00:00–23:59). Append (:[0-5]\d)? for optional seconds. See the 24-hour time pattern.
How to validate credit card numbers using regex?
Validate the digit structure per network — e.g. Visa ^4\d{12}(\d{3})?$, Mastercard ^5[1-5]\d{14}$ — then verify the checksum with the Luhn algorithm, which regex cannot do. See our credit-card patterns.
Source: ISO/IEC 7812-1 — card issuer numbers
How to match a valid MAC address using regex?
Use ^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$ to match six hex pairs separated by colons or hyphens. See the MAC-address pattern.
Source: IEEE Registration Authority — MAC/EUI
How to validate standard UUIDs/GUIDs with regex?
A standard UUID is ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$. To enforce version 4 specifically, see our UUID-v4 and generic UUID patterns.
Source: RFC 9562 — UUID
How to match valid zip codes (US/Global formats)?
US ZIP: ^\d{5}(-\d{4})?$ matches a 5-digit code or ZIP+4. Postal formats differ worldwide, so match the country you target rather than one universal pattern. See the US ZIP pattern.
How to match a hex color code using regex?
Use ^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$ to match 3- or 6-digit hex colors such as #fff or #ffffff. Extend to {8} for an alpha channel. See the hex-color pattern.
How to match a valid floating-point decimal number?
Use ^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$ to match integers, decimals, and scientific notation. For a plain decimal only, ^-?\d+\.\d+$ is enough.
How to write a regex to match valid JSON format?
Regex cannot reliably validate full JSON — it is a nested structure and regex is not built for arbitrary nesting. Parse it instead (JSON.parse in JavaScript, json.loads in Python) and catch the error. Regex is fine for pulling out individual keys — see our JSON-key pattern.
Source: RFC 8259 — JSON
How to check if a string is a valid Base64 using regex?
Use ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ to match standard padded Base64. See the Base64 pattern.
Source: RFC 4648 — Base64
How to match semantic version numbers (SemVer) with regex?
The official-style SemVer regex is ^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$, matching MAJOR.MINOR.PATCH with optional pre-release and build metadata. See the SemVer pattern.
Source: Semantic Versioning 2.0.0
How to validate an Indian Aadhaar or PAN card using regex?
Indian PAN: ^[A-Z]{5}\d{4}[A-Z]$. Aadhaar (12 digits, not starting with 0 or 1): ^[2-9]\d{11}$. These check format only — the Aadhaar Verhoeff checksum cannot be done in pure regex. See our PAN and Aadhaar patterns.
Source: UIDAI (Aadhaar), Income Tax Dept (PAN)
How to match valid CSS class and ID names?
A valid CSS identifier is ^-?[_a-zA-Z][_a-zA-Z0-9-]*$ — it cannot start with a digit (or a digit right after a hyphen). See our CSS class and CSS id patterns.
How to match a string without special characters?
Whitelist what you allow rather than blacklisting. ^[A-Za-z0-9 ]+$ permits only letters, digits, and spaces, so anything else fails. To simply detect a special character, test for [^A-Za-z0-9].
Extracting & replacing text
How to extract URLs from text using regex?
A workable pattern is https?:\/\/[^\s]+, which grabs an http or https URL up to the next whitespace. URLs are notoriously varied, so for careful work use our tested URL pattern.
How to extract domain names from URLs using regex?
Capture the host from a URL with https?:\/\/([^\/\s:]+) — group 1 is the domain. To validate a bare domain instead, see our domain-name pattern.
How to strip HTML tags using regex?
A quick strip is <[^>]+>, replacing matches with an empty string. Be warned: regex cannot safely parse arbitrary HTML — comments, scripts, and quoted angle brackets break it — so for real documents use an HTML/DOM parser.
How to find duplicate words using regex?
Use a backreference with word boundaries: \b(\w+)\s+\1\b matches a word immediately repeated. Add the i flag to catch "the The" and the g flag to find every occurrence.
How to split a string using regex?
Pass a regex as the delimiter to your language's split function. JavaScript str.split(/\s+/) splits on any run of whitespace; Python re.split(r'[,;]\s*', s) splits on commas or semicolons. A regex delimiter lets you split on variable separators a fixed string cannot express.
How to replace multiple spaces with a single space using regex?
Match a run of whitespace and replace it with a single space: str.replace(/\s+/g, ' ') in JavaScript, or re.sub(r'\s+', ' ', s) in Python. Chain .trim() to also drop leading and trailing spaces.
How to extract text between parentheses using regex?
Use a negated class inside a capture: \(([^)]*)\) — group 1 holds the text inside each pair of parentheses. Because [^)]* stops at the first closing paren, multiple pairs are matched separately.
How to match everything up to a specific character?
Use a negated class: ^[^,]* matches everything up to the first comma. To match up to but not including a character elsewhere in the string, use a lazy match with a lookahead like .*?(?=,).
How to match a string between two specified strings?
Use a lazy capture between the two delimiters: START(.*?)END captures the middle in group 1. Add the dotAll (s) flag if the content can span multiple lines.
How to remove all emojis from a string using regex?
Match emoji Unicode ranges with the u flag, e.g. str.replace(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/gu, ''). Emojis span many blocks, so for full coverage use the property escape \p{Extended_Pictographic} where it is supported.
Source: Unicode UTS #51 — Emoji
How to extract Twitter handles / mentions using regex?
Match an @-mention with (?<=^|\s)@(\w{1,15})\b — up to 15 word characters after an @, at a boundary. See the Twitter-handle pattern.
How to match HTML attributes using regex?
Capture name/value pairs with (\w+)\s*=\s*"([^"]*)" — group 1 is the attribute name and group 2 the value. This works for simple, well-formed tags; use a real HTML parser for messy markup.
How to parse JSON keys using regex patterns?
Match keys with "([^"]+)"\s*: — group 1 is each key name that precedes a colon. For anything beyond quick extraction, parse the JSON properly. See the JSON-key pattern.
How to extract data from a CSV line using regex?
A quote-aware field pattern is ("[^"]*"|[^,]*)(,|$). Because quoted commas and escaped quotes break naive patterns, prefer a real CSV parser for production data and keep regex for simple, well-formed lines.
How to match a specific file extension using regex?
Capture the extension with \.([a-zA-Z0-9]+)$ — group 1 is the text after the last dot. To match specific types, use \.(jpg|png|gif)$ with the i flag.
How to match currency symbols and amounts with regex?
Match a symbol and a formatted amount with [$€£]\s?\d{1,3}(,\d{3})*(\.\d{2})?. See our currency patterns such as USD and EUR.
How to match a specific word using regex?
Wrap the word in boundaries: \bword\b matches "word" but not "wordy" or "sword". Add the i flag for a case-insensitive match.
How to match strings containing specific words?
Use one lookahead per required word: ^(?=.*apple)(?=.*banana).*$ matches any line that contains both, in any order. Each (?=.*word) is an independent "must contain" assertion.
How to isolate words starting with a specific letter?
Use a boundary plus the letter: \bs\w* matches every word beginning with "s". Add the i flag to include capitals and the g flag to collect them all.
How to extract hex codes from CSS files using regex?
Match color hexes with #[0-9a-fA-F]{3,8}\b, capturing 3-, 6-, or 8-digit values. See the hex-color pattern.
How to match trailing and leading whitespaces for trimming?
Match edge whitespace with ^\s+|\s+$ and replace it with an empty string — the regex equivalent of trim. A built-in .trim() is faster; reach for the regex when trimming inside a larger replacement.
How to use regex to format integers with thousand separators?
Insert commas with a lookahead: str.replace(/\B(?=(\d{3})+(?!\d))/g, ',') turns 1234567 into 1,234,567. It matches every position that has a multiple of three digits remaining to its right.
How to build a markdown link parsing regex?
Match \[([^\]]+)\]\(([^)]+)\) — group 1 is the link text and group 2 the URL. See the Markdown-link pattern.
How to write a regex pattern for YouTube video URLs?
Extract the 11-character video ID with (?:youtu\.be\/|v=)([\w-]{11}), which handles both youtu.be and watch?v= forms. See the YouTube-video-ID pattern.
How to write a regex for absolute file paths?
Unix: ^\/(?:[^\/\0]+\/)*[^\/\0]+$. Windows: ^[A-Za-z]:\\(?:[^\\\/:*?"<>|]+\\?)*$. Match the operating system you target, since separators and drive letters differ.
How to target HTML comments using regex?
Match with <!--[\s\S]*?--> — the [\s\S] lets it span lines and the lazy *? stops at the first "-->". See the HTML-comment pattern.
How to filter comments (block and inline) using regex?
Match both C-style forms with \/\/[^\n]*|\/\*[\s\S]*?\*\/: the first alternative catches inline // comments, the second catches /* ... */ blocks. The lazy *? keeps a block from swallowing later code.
How to check if a string contains numbers using regex?
Test for a single digit anywhere with \d — /\d/.test(str) in JavaScript returns true if any digit is present. Anchor it, as in ^\D*\d, only when the position matters.
How to extract all numbers from a text string using regex?
Use a global match rather than an anchored one: str.match(/\d+/g) in JavaScript or re.findall(r'\d+', text) in Python returns every run of digits as a list. To also capture negatives and decimals, widen the pattern to -?\d+(?:\.\d+)?.
Language & tool specifics
How to use regex in JavaScript?
Create a pattern with a literal /pattern/flags or new RegExp('pattern','flags'), then use test() for true/false, match() or matchAll() to extract, and replace() to substitute. Add the g flag to act on every match.
Source: MDN — JavaScript RegExp
How to use regex in Python?
Import re and use re.search (find anywhere), re.match (anchor at the start), re.findall (all matches), and re.sub (replace). Use raw strings like r'\d+' so Python does not consume the backslashes.
Source: Python re — documentation
How to use regex in Java?
Compile with Pattern.compile("\\d+"), then drive a Matcher: m.find(), m.matches(), m.group(). Java string literals need doubled backslashes, so \d is written \\d.
Source: Oracle Java — Pattern
How to use regex in C# / .NET?
Use System.Text.RegularExpressions.Regex with Regex.IsMatch, Regex.Match, and Regex.Replace. Verbatim strings such as @"\d+" avoid double-escaping, and .NET supports named groups and variable-length lookbehind.
How to use regular expressions in PHP?
Use the PCRE functions with delimiters: preg_match('/\d+/', $s), preg_match_all for every match, and preg_replace to substitute. The pattern must be wrapped in delimiters, usually forward slashes.
Source: PHP — PCRE functions
How to use regex in Golang?
Import regexp and compile with regexp.MustCompile(`\d+`), then call MatchString, FindAllString, or ReplaceAllString. Go uses the RE2 engine — linear-time and safe from catastrophic backtracking, but without lookaround or backreferences.
Source: Go — regexp package
How to use regex in Ruby?
Use literals like /\d+/ with =~, String#match, scan (all matches), and gsub (global replace). Named captures via (?<name>) can be read straight into local variables.
Source: Ruby — Regexp class
How to use regex in Bash/Shell scripting?
Use [[ $var =~ regex ]] with ERE syntax (no slashes, and do not quote the pattern), then read groups from ${BASH_REMATCH[@]}. For streams, grep -E, sed -E, and awk apply regex line by line.
How to use regex in PowerShell?
Use the -match and -replace operators or the [regex] class. After a successful -match, captured groups are available in the automatic $Matches hashtable.
How to use regex in SQL (REGEXP_LIKE)?
Use your database's native regex operator: REGEXP_LIKE(col, '^[0-9]+$') in Oracle and MySQL 8+, or the ~ operator in PostgreSQL (col ~ '^[0-9]+$'). Support varies by engine — SQL Server needs CLR for real regex — so check your database's flavor before using advanced tokens.
How to run a case-insensitive regex match inside an SQL query?
Add a case-insensitivity flag or operator: REGEXP_LIKE(col, '^abc', 'i') in Oracle and MySQL 8+, or PostgreSQL's ~* operator (col ~* '^abc'). In older MySQL, REGEXP instead follows the column's collation, so a _ci collation already matches case-insensitively.
How to filter search queries using custom regex in Google Search Console?
In the Performance report, open the Query filter and choose "Custom (regex)". Search Console uses RE2 syntax, which has no lookaheads — so to split brand from non-brand, pick the "Doesn't match regex" option with a pattern like brandname|brand name, rather than a (?!...) pattern. To surface question-style long-tail keywords, use "Matches regex" with ^(who|what|when|where|why|how|is|can|does)\b. Add the inline (?i) flag when you need to force case-insensitive matching.
How to use regex in Google Sheets?
Use the built-ins: REGEXMATCH(A1,"^\d+$") returns TRUE/FALSE, REGEXEXTRACT pulls out the first match, and REGEXREPLACE substitutes. Sheets uses RE2 syntax, so lookaround and backreferences are not available.
How to use regex in Excel formulas?
Excel 365 added native REGEXTEST, REGEXEXTRACT, and REGEXREPLACE functions; older versions need VBA's CreateObject("VBScript.RegExp"). The new functions use a PCRE-style flavor.
How to use regex in R programming?
Base R uses grepl to test, regmatches with regexpr to extract, and gsub to replace; pass perl=TRUE for PCRE features. The stringr package (str_detect, str_extract) offers a friendlier interface.
How to use regular expressions in C++ (std::regex)?
Include <regex> and use std::regex with std::regex_match, std::regex_search, and std::regex_replace. Raw string literals like R"(\d+)" spare you from escaping backslashes.
How to use regex search in Notepad++?
Open Find or Replace (Ctrl+H), tick "Regular expression", then search or replace. Notepad++ uses the Boost/PCRE flavor, and you reference captured groups in the replace box as $1, $2, and so on.
How to use regex replace in VS Code?
In Find/Replace (Ctrl+H) click the .* icon to enable regex. Reference capture groups in the replace field with $1, $2; VS Code uses JavaScript regex syntax and supports multiline search.
How to convert regex patterns between PCRE and JavaScript flavors?
Most core syntax is identical, but the differences bite: JavaScript lacks \A/\Z (use ^/$), possessive quantifiers, and recursion, while named groups use (?<name>) in both modern engines. Our flavor converter translates a pattern between PCRE, JavaScript, and other flavors automatically.
How to split a string in Java?
Use String.split, which takes a regex: "a,b;c".split("[,;]"). Pass a limit as the second argument to cap the number of pieces, and escape metacharacters — to split on a literal dot, use "\\.".
How to split a string in Python?
For a fixed delimiter use s.split(','); for a pattern use re.split(r'[,;]\s*', s). re.split lets you divide on variable separators like a run of whitespace, r'\s+'.
How to split a string in JavaScript?
Use str.split(separator), where the separator is a string or a regex. "a1b2c".split(/\d/) splits on any digit — a regex separator lets you break on patterns a plain string cannot express.
How to check if a string contains a substring in Python?
To simply check membership, use 'sub' in text — no regex needed and it is faster. For a pattern-based check, use re.search(r'pattern', text), which returns a match object (truthy) or None.
How to validate email in JavaScript?
Test with /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email), which returns true or false. For most forms, a native <input type="email"> plus this light check is enough; avoid over-strict patterns that reject valid addresses. See the email pattern.
Performance & security
What is catastrophic backtracking in regex?
It happens when nested or overlapping quantifiers — like (a+)+ — force the engine to try exponentially many ways to match a failing string, hanging your program. Avoid ambiguous nesting, use atomic or possessive groups where supported, and prefer specific character classes over .*.
Source: OWASP — ReDoS
What is ReDoS (Regex Denial of Service)?
Regular-expression Denial of Service is an attack that feeds crafted input to a vulnerable pattern to trigger catastrophic backtracking and exhaust CPU. Defend by avoiding nested quantifiers, adding timeouts, or using a linear-time engine like RE2, and never run untrusted patterns against untrusted input. Source: OWASP — ReDoS
How to use regex to find SQL injection patterns?
Regex is a weak defense against SQL injection — attackers slip past keyword blacklists easily. Use parameterized queries and prepared statements instead. If you must scan, flags such as ('|--|;|\b(UNION|SELECT|DROP)\b) can surface suspicious input for logging, not as your primary control.
Source: OWASP — SQL Injection
How to parse Cron expressions using regex?
A five-field cron line can be matched field by field; a permissive shape is ^(\S+\s+){4}\S+$, but validating real ranges needs a longer pattern. See our cron-expression pattern.
Source: POSIX crontab (The Open Group)