PageSourceSearch

https://regex101.com/static/codeGeneratorDialog.b472608bd55a6f08b223.chunk.js

js regex101.com collected 2026-09-24 08:32:36 UTC 32,192 bytes, 1 lines download raw bytes

1!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{};e.SENTRY_RELEASE={id:"v14.1.0"};var t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5797d01b-9e70-4c05-9d3c-1d34075200de",e._sentryDebugIdIdentifier="sentry-dbid-5797d01b-9e70-4c05-9d3c-1d34075200de")}catch(e){}}(),(("undefined"!=typeof self?self:this).webpackChunk_r101_web=("undefined"!=typeof self?self:this).webpackChunk_r101_web||[]).push([[4023],{91769(e,t,n){n.d(t,{CodeGeneratorDialogPopup:()=>Ee});var a=n(47075),r=n(14041),s=n(89924),p=n(86116),i=n(845),d=n(14603),o=n(4174),l=n(82025),u=n(79088),c=n(17200),g=n(17380),h=n(69527),m=n(13176),f=n(18940),x=n(84574),b=n(53986),S=n(54221);const $=class{string="";indentLevel=0;constructor(e=""){this.string=e}indent(e,t=0){return" ".repeat(t)+e}append(e="",t){this.string+=this.indent(`${e}\n`,this.indentLevel),null!=t&&(this.indentLevel=t)}toString(){return this.string}};var y=n(11896),A=n(31085);const R=({lang:e,children:t})=>{const n=(0,r.useRef)(null);return(0,r.useEffect)(()=>{null!=n.current&&y.A.highlightElement(n.current)},[t]),(0,A.jsx)("code",{className:e,ref:n,children:t})},_=(e,t)=>y.A.registerLanguage(e,t);function v(e){return e.replace(/\n/g,'" & @CRLF & _\n                "')}_("autoit",S.A);const w=e=>{const t=e.regex,n=e.flags,a=e.testString,r=e.isSubstituting,s=e.substString,p=e.isGlobal,i=new $,d=n.replace("g",""),o=v(t),l=v(a),u=v(s);return r?i.append("#include <MsgBoxConstants.au3> ; to declare the Constants of MsgBox"):(i.append("#include <StringConstants.au3> ; to declare the Constants of StringRegExp"),i.append("#include <Array.au3> ; UDF needed for _ArrayDisplay and _ArrayConcatenate")),i.append(""),i.append(`Local $sRegex = "${d.length>0?`(?${d})`:""}${o}"`),i.append(`Local $sString = "${l}"`),r?(i.append(`Local $sSubst = "${u}"`),i.append(""),i.append("Local $sResult = StringRegExpReplace($sString, $sRegex, $sSubst)"),i.append(""),i.append('MsgBox($MB_SYSTEMMODAL, "Result", $sResult)')):(i.append(""),p?(i.append("Local $aArray = StringRegExp($sString, $sRegex, $STR_REGEXPARRAYGLOBALFULLMATCH)"),i.append("Local $aFullArray[0]"),i.append("For $i = 0 To UBound($aArray) -1"),i.append("    _ArrayConcatenate($aFullArray, $aArray[$i])"),i.append("Next"),i.append("$aArray = $aFullArray")):i.append("Local $aArray = StringRegExp($sString, $sRegex, $STR_REGEXPARRAYFULLMATCH)"),i.append(""),i.append("; Present the entire match result"),i.append('_ArrayDisplay($aArray, "Result")')),(0,A.jsx)(R,{lang:"autoit",children:i.toString()})},E=(0,r.memo)(w);var I=n(67090),C=n(20002);const P=e=>{let t="r101";for(;e.includes(`)${t}"`);)t+="_";return`R"${t}(${e})${t}"`};_("cpp",C.A);const N=e=>(0,A.jsx)(R,{lang:"cpp",children:T(e)}),T=e=>{const t=e.regex,n=e.flags,a=e.flavor,r=e.testString,s=e.isSubstituting,p=e.substString,i=e.isGlobal,d=new $,o=[a===I.oI.POSIX_BRE?"boost::regex_constants::basic":"boost::regex_constants::extended",n.includes("i")?"boost::regex_constants::icase":null].filter(e=>null!=e),l=["boost::regex_constants::match_default",n.includes("m")?null:"boost::regex_constants::match_single_line",n.includes("s")?null:"boost::regex_constants::match_not_dot_newline",!i&&s?"boost::regex_constants::format_first_only":null].filter(e=>null!=e);return d.append("// Requires Boost.Regex built with ICU support."),d.append("// Compile this source as UTF-8 and link against Boost.Regex and ICU."),d.append("#include <boost/regex/icu.hpp>"),d.append("#include <iostream>"),d.append("#include <string>"),d.append(""),d.append("int main() {",4),d.append(`const std::string pattern = ${P(t)};`),d.append(`const std::string input = ${P(r)};`),s&&d.append(`const std::string substitution = ${P(p)};`),d.append(`const auto expression = boost::make_u32regex(pattern, ${o.join(" | ")});`),d.append(`const boost::regex_constants::match_flag_type flags = ${l.join(" | ")};`),d.append(""),s?(d.append("const std::string result = boost::u32regex_replace(input, expression, substitution, flags);"),d.append("std::cout << result << '\\n';",0)):i?(d.append("auto iterator = boost::make_u32regex_iterator(input, expression, flags);"),d.append("const boost::u32regex_iterator<std::string::const_iterator> end;"),d.append("for (; iterator != end; ++iterator) {",8),d.append("const auto& match = *iterator;"),d.append("for (std::size_t group = 0; group < match.size(); ++group) {",12),d.append('std::cout << "Group " << group << ": " << match[group] << \'\\n\';',8),d.append("}",4),d.append("}",0)):(d.append("boost::smatch match;"),d.append("if (boost::u32regex_search(input, match, expression, flags)) {",8),d.append("for (std::size_t group = 0; group < match.size(); ++group) {",12),d.append('std::cout << "Group " << group << ": " << match[group] << \'\\n\';',8),d.append("}",4),d.append("}",0)),d.append("}"),d.toString()},G=(0,r.memo)(N);_("cpp",C.A);const j=e=>(0,A.jsx)(R,{lang:"cpp",children:O(e)}),O=e=>
1{const t=e.regex,n=e.flags,a=e.flavor,r=e.testString,s=e.isSubstituting,p=e.substString,i=e.isGlobal,d=new $,o=a===I.oI.POSIX_ERE||a===I.oI.POSIX_BRE,l=[a===I.oI.POSIX_BRE?"std::regex_constants::basic":a===I.oI.POSIX_ERE?"std::regex_constants::extended":"std::regex_constants::ECMAScript",n.includes("i")?"std::regex_constants::icase":null,n.includes("m")&&!o?"std::regex_constants::multiline":null].filter(e=>null!=e);if(d.append(o?"// Uses std::regex POSIX pattern syntax and ECMAScript replacement syntax.":"// Uses std::regex ECMAScript pattern and replacement syntax."),n.includes("m")&&o?d.append("// The multiline flag has no portable POSIX std::regex equivalent and is omitted."):n.includes("m")&&d.append("// The multiline option requires C++17 or newer."),n.includes("s")&&d.append("// The dotall flag has no portable std::regex equivalent and is omitted."),d.append("#include <iostream>"),d.append("#include <regex>"),d.append("#include <string>"),d.append(""),d.append("int main() {",4),d.append(`const std::string pattern = ${P(t)};`),d.append(`const std::string input = ${P(r)};`),s&&d.append(`const std::string substitution = ${P(p)};`),d.append(`const std::regex expression(pattern, ${l.join(" | ")});`),d.append(""),s){const e=["std::regex_constants::format_default",i?null:"std::regex_constants::format_first_only"].filter(e=>null!=e);d.append(`const auto formatFlags = ${e.join(" | ")};`),d.append("const std::string result = std::regex_replace(input, expression, substitution, formatFlags);"),d.append("std::cout << result << '\\n';",0)}else i?(d.append("std::sregex_iterator iterator(input.cbegin(), input.cend(), expression);"),d.append("const std::sregex_iterator end;"),d.append("for (; iterator != end; ++iterator) {",8),d.append("const auto& match = *iterator;"),d.append("for (std::size_t group = 0; group < match.size(); ++group) {",12),d.append('std::cout << "Group " << group << ": " << match[group].str() << \'\\n\';',8),d.append("}",4),d.append("}",0)):(d.append("std::smatch match;"),d.append("if (std::regex_search(input, match, expression)) {",8),d.append("for (std::size_t group = 0; group < match.size(); ++group) {",12),d.append('std::cout << "Group " << group << ": " << match[group].str() << \'\\n\';',8),d.append("}",4),d.append("}",0));return d.append("}"),d.toString()},M=(0,r.memo)(j);_("csharp",n(33496).A);const L=e=>e.replace(/("")|"/g,(e,t)=>t||'""'),k=e=>(0,A.jsx)(R,{lang:"csharp",children:B(e)}),B=e=>{const t=e.regex,n=e.delimiter,a=e.flags,r=e.testString,s=e.isSubstituting,p=e.substString,i=e.isGlobal,d=e.flavor,o=F(a),l=new $,u=d===I.oI.DOTNET?`@${n}${'"'!==n?"\n":""}`:'@"',c=d===I.oI.DOTNET?'"'===n?'"':"\n"+n:'"',g=`${u}${L(t)}${c}`;return l.append("using System;"),l.append("using System.Text.RegularExpressions;"),l.append(""),s&&l.append(`string substitution = @"${L(p)}";`),l.append(`string input = @"${L(r)}";`),l.append(""),s?(l.append(`string result = Regexes.Pattern().Replace(input, substitution${i?"":", 1"});`),l.append("Console.WriteLine(result);")):i?(l.append("foreach (Match match in Regexes.Pattern().Matches(input))"),l.append("{",4),l.append(`Console.WriteLine("${(0,x.Ay)("'{0}' found at index {1}","{1}")}.", match.Value, match.Index);`,0),l.append("}")):(l.append("Match match = Regexes.Pattern().Match(input);"),l.append(`Console.WriteLine("${(0,x.Ay)("'{0}' found at index {1}","{1}")}", match.Value, match.Index);`)),l.append(""),l.append("internal static partial class Regexes"),l.append("{",4),l.append(`[GeneratedRegex(${g}${o?`, ${o}`:""})]`),l.append("internal static partial Regex Pattern();",0),l.append("}"),l.toString()},F=e=>e.split("").map(e=>{switch(e){case"i":return"RegexOptions.IgnoreCase";case"x":return"RegexOptions.IgnorePatternWhitespace";case"m":return"RegexOptions.Multiline";case"s":return"RegexOptions.Singleline";case"n":return"RegexOptions.ExplicitCapture";case"u":return"RegexOptions.CultureInvariant";case"R":return"RegexOptions.RightToLeft";case"N":return"RegexOptions.NonBacktracking";default:return""}}).filter(Boolean).join(" | "),U=(0,r.memo)(k);var D=n(80431);function W(e,...t){if(!t||0===t.length)return e;let n=0,a="";for(let r=0,s=e.length;r<s;r++){const s=e.charAt(r);t.includes(s)&&n%2==0?(a+="\\"+s,n=0):(a+=s,"\\"===s?n++:n=0)}return n%2!=0&&(a+="\\"),a}function X(e,...t){if(!t||0===t.length)return e;let n="";for(let a=0,r=e.length;a<r;a++){const r=e.charAt(a);t.includes(r)?n+="\\"+r:n+=r}return n}_("go",n(69273).A);const q=e=>{const t=e.regex,n=e.flags,a=e.testString,r=e.isSubstituting,s=e.substString,p=e.isGlobal,i=new $,d=(0,D.M1)(I.oI.GOLANG,n).replace("g",""),o=d?`(?${d})`:"";return i.append("package main"),i.append(""),i.append("import (",4),i.append('"regexp"'),i.append('"fmt"',0),i.append(")"),i.append(""),i.append("func main() {",4),i.append(`var re = regexp.MustCompile(\`${o}${t}\`)`),r&&!p?(i.append(`var str = []byte(\`${X(a,"`")}\`)`),i.append(`var substitution = []byte("${s}")`),i.append("var count = 1 // negative counter is equivalent to global case (replace all)"),i.append(""),i.append("str = re.ReplaceAllStringFunc(str, func(s string) string {",8),i.append("if count == 0 {",12),i.append("return s",8),i.append("}"),i.append(""),i.append("count -= 1"),i.append("return re.ReplaceAllString(s, substitution)",4),i.append("})"),i.append(""),i.append("fmt.Println(string(str))",0)):r?(i.append(`var str = \`${X(a,"`")}\``),i.append(`var substitution = "${s}"`),i.append(""),i.append("fmt.Println(re.ReplaceAllString(str, substitution))",0)):p?(i.append(`var str = \`${X(a,"`")}\``),i.append(""),i.append("for i, match := range re.FindAllString(str, -1) {",8),i.append('fmt.Println(match, "found at index", i)',4),i.append("}",0)):(i.append(`var str = \`${X(a,"`")}\``),i.append(""),i.append("if len(re.FindStringIndex(str)) > 0 {",8),i.append('fmt.Println(re.FindString(str),"found at index",re.FindStringIndex(str)[0])',4),i.append("}",0)),i.append("}"),(0,A.jsx)(R,{lang:"go",children:i.toString()})},V=(0,r.memo)(q),Y=e=>`'${e.replaceAll("'","'\\''")}'`,z=e=>(0,A.jsx)(R,{lang:"common",children:H(e)}),H=e=>
1{const t=e.regex,n=e.flags,a=e.flavor,r=e.testString,s=e.isSubstituting,p=e.isGlobal,i=new $;if(s)return i.append("# grep does not perform substitutions; use the sed generator instead."),i.toString();n.includes("s")&&i.append("# grep has no direct equivalent for the dotall flag; it is omitted."),n.includes("m")||i.append("# grep processes input one line at a time, so non-multiline anchors may behave differently.");const d=[a===I.oI.POSIX_ERE?"-E":null,n.includes("i")?"-i":null,"-o"].filter(e=>null!=e),o=`printf '%s' ${Y(r)} | grep ${d.join(" ")} -- ${Y(t)}`;return i.append(p?o:`${o} | head -n 1`),i.toString()},J=(0,r.memo)(z);_("java",n(3559).A);const Z=e=>{const t=e.match(/[^\n]+\n*|\n+/g);return t?t.map(e=>'\t + "'+X(e,"\\",'"').replace(/\n/g,"\\n")+'"').join("\n").slice(4):'"'+X(e,"\\",'"')+'"'},Q=e=>{const t=e.regex,n=e.flags,a=e.testString,r=e.isSubstituting,s=e.substString,p=e.isGlobal,i=new $,d=n.split("").map(e=>{switch(e){case"i":return"Pattern.CASE_INSENSITIVE | ";case"x":return"Pattern.COMMENTS | ";case"m":return"Pattern.MULTILINE | ";case"s":return"Pattern.DOTALL | ";case"u":return"Pattern.UNICODE_CASE | ";case"U":return"Pattern.UNICODE_CHARACTER_CLASS | ";case"d":return"Pattern.UNIX_LINES | ";default:return""}}).join("").replace(/ \| $/,"");return i.append("import java.util.regex.Matcher;"),i.append("import java.util.regex.Pattern;"),i.append(""),i.append("public class Example {",4),i.append("public static void main(String[] args) {",8),i.append(`final String regex = ${Z((e=>e.replace(/(\\*)(\\[pPx]{[^}]+}|{\d+,?\d*}|[{}])/g,(e,t,n)=>t.length%2!=0||"{"!==n&&"}"!==n?t+n:t+"\\"+n))(t))};`),i.append(`final String string = ${Z(a)};`),r&&i.append(`final String subst = ${Z(s)};`),i.append(""),""===d?i.append("final Pattern pattern = Pattern.compile(regex);"):i.append(`final Pattern pattern = Pattern.compile(regex, ${d});`),i.append("final Matcher matcher = pattern.matcher(string);"),i.append(""),r?(i.append("// "+(0,x.Ay)("The substituted value will be contained in the result variable")),p?i.append("final String result = matcher.replaceAll(subst);"):i.append("final String result = matcher.replaceFirst(subst);"),i.append(""),i.append(`System.out.println("${(0,x.Ay)("Substitution result")}: " + result);`,4)):(p?i.append("while (matcher.find()) {",12):i.append("if (matcher.find()) {",12),i.append(`System.out.println("${(0,x.Ay)("Full Match")}: " + matcher.group(0));`),i.append(""),i.append("for (int i = 1; i <= matcher.groupCount(); i++) {",16),i.append(`System.out.println("${(0,x.Ay)("Group")} " + i + ": " + matcher.group(i));`,12),i.append("}",8),i.append("}",4)),i.append("}",0),i.append("}"),(0,A.jsx)(R,{lang:"java",children:i.toString()})},K=(0,r.memo)(Q);_("javascript",n(83928).A);const ee=e=>{const t=e.regex,n=e.delimiter,a=e.flags,r=e.testString,s=e.isSubstituting,p=e.substString,i=e.isGlobal,d=new $,o=(0,D.M1)(I.oI.JAVASCRIPT,a),l="/"===n;l&&(d.append(`const regex = /${t}/${o};`),d.append(""),d.append("// Alternative syntax using RegExp constructor"));const u=X(t,"\\",l?"/":"'");return d.append(`${l?"// ":""}const regex = new RegExp('${X(u,"'")}', '${o}')`),l&&d.append(""),d.append(`const str = \`${X(r,"$","`","\\")}\`;`),s?(d.append(`const subst = \`${X(p,"`")||""}\`;`),d.append(""),d.append("// "+(0,x.Ay)("The substituted value will be contained in the result variable")),d.append("const result = str.replace(regex, subst);"),d.append(""),d.append("console.log('Substitution result: ', result);")):(d.append(""),d.append("// Reset `lastIndex` if this regex is defined globally"),d.append("// regex.lastIndex = 0;"),d.append(""),d.append("let m;"),d.append(""),d.append((i?"while":"if")+" ((m = regex.exec(str)) !== null) {",4),i&&(d.append("// "+(0,x.Ay)("This is necessary to avoid infinite loops with zero-width matches")),d.append("if (m.index === regex.lastIndex) {",8),d.append("regex.lastIndex++;",4),d.append("}"),d.append("")),d.append("// "+(0,x.Ay)("The result can be accessed through the `m`-variable.")),d.append("m.forEach((match, groupIndex) => {",8),d.append("console.log(`Found match, group ${groupIndex}: ${match}`);",4),d.append("});",0),d.append("}")),(0,A.jsx)(R,{lang:"js",children:d.toString()})},te=(0,r.memo)(ee);var ne=n(56740);_("perl",n(47450).A);const ae=e=>
1{const t=e.regex,n=e.flags,a=e.delimiter,r=e.testString,s=e.isSubstituting,p=e.substString,i=e.isGlobal,d=new $,o=(0,D.an)(I.oI.PCRE2,a),l=(0,D.M1)(I.oI.PCRE2,n).replace(/[A-Zg]/g,""),u=W(t,o);return d.append("use strict;"),d.append(""),d.append(`my $str = '${X(r,"'","\\")}';`),d.append(`my $regex = qr${o}${u}${o}${l}p;`),s?(d.append(`my $subst = '${X(p,"'","\\")}';`),d.append(""),d.append(`my $result = $str =~ s${o}$regex${o}$subst${o}r`+(i?"g":"")+";"),d.append(""),d.append(`print "${(0,x.Ay)("The result of the substitution is")}' $result\\n";`)):(d.append(""),d.append("if ( $str =~ /$regex/"+(i?"g":"")+" ) {",2),d.append(`print "${(0,x.Ay)("Whole match is {1} and its start/end positions can be obtained via {2} and {3}","${^MATCH}","\\$-[0]","\\$+[0]")}\\n";`),d.append(`# print "${(0,x.Ay)("Capture Group {1} is {2} and its start/end positions can be obtained via {3} and {4}","1","$1","\\$-[1]","\\$+[1]")}\\n";`),d.append(`# print "${(0,x.Ay)("Capture Group {1} is {2} ... and so on","2","$2")}\\n";`,0),d.append("}"),d.append(""),d.append(`# ${(0,x.Ay)("{1} and {2} are also available with the use of '{3}'","${^POSTMATCH}","${^PREMATCH}","/p")}`),d.append(`# ${(0,x.Ay)("Named capture groups can be called via {1}","$+{name}")}`)),(0,A.jsx)(R,{lang:"perl",children:d.toString()})},re=(0,r.memo)(ae);_("php",n(42511).A);const se=e=>{const t=e.regex,n=e.flags,a=e.delimiter,r=e.testString,s=e.isSubstituting,p=e.substString,i=e.isGlobal,d=new $,o=(0,D.an)(I.oI.PCRE2,a),l=(0,D.M1)(I.oI.PCRE2,n).replace("g",""),u=X(W(t,o),"\\","'");return d.append(`$re = '${o}${u}${o}${l}';`),d.append(`$str = '${X(r,"'","\\")}';`),s?(d.append(`$subst = '${X(p,"\\","'")}';`),d.append(""),d.append("$result = preg_replace($re, $subst, $str"+(i?"":", 1")+");"),d.append(""),d.append('echo "'+(0,x.Ay)("The result of the substitution is")+' ".$result;')):(d.append(""),i?d.append("preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);"):d.append("preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE, 0);"),d.append(""),d.append("// Print the entire match result"),d.append("var_dump($matches);")),(0,A.jsx)(R,{lang:"php",children:d.toString()})},pe=(0,r.memo)(se);var ie=n(64402),de=n(30219);_("python",ie.A);const oe=(e,t='"',n=!1)=>{const a=e.match(/[^\n]+\n*|\n+/g),r=t[0],s=n?"r":"",p=n?e=>W(e,r):e=>X(e,"\\",r);return/\n/.test(e)?"("+(a??[]).map(e=>"\t"+s+t+p(e).replace(/\n/g,"\\n")+t).join("\n").slice(1)+")":s+t+p(e)+t},le=e=>{const t=e.regex,n=e.delimiter,a=e.testString,r=e.flags,s=e.isSubstituting,p=e.substString,i=e.isGlobal,d=new $,o=r.split("").map(e=>{switch(e){case"i":return"re.IGNORECASE";case"m":return"re.MULTILINE";case"s":return"re.DOTALL";case"u":default:return null;case"x":return"re.VERBOSE";case"a":return"re.ASCII"}}).filter(e=>null!=e).join(" | "),l=o?", flags="+o:"",u=(0,D.an)(I.oI.PYTHON,n),c=(0,I.rG)(t,{delimiter:n,flags:r,flavor:I.oI.PYTHON,featureFlags:de.o,invalidFlagsBehavior:"sanitize"}).tokens[0].stateData.flags.current.includes("x");if(d.append("import re"),d.append(""),d.append(`pattern = re.compile(${((e,t,n=!1)=>
1{if(n){const n=1===t.length?t.repeat(3):t;return"r"+n+"\n"+W(e,n[0]).trim().split("\n").map(e=>"\t"+e).join("\n")+"\n\t"+n}return oe(e,t,!0)})(t,u,c)}${l})`),d.append(""),d.append(`test_string = ${oe(a)}`),d.append(""),s){d.append(`substitution = ${oe(p)}`),d.append("");const e=i?"":", count=1";d.append(`result = pattern.sub(substitution, test_string${e})`),d.append(""),d.append("print(result)")}else{let e,t;i?(e=(0,x.Ay)("Match {1} was found at {2}","{match_num}","{match.start()}-{match.end()}"),t=(0,x.Ay)("Group {1} found at {2}","{group_num}","{match.start(group_num)}-{match.end(group_num)}"),d.append("matches = pattern.finditer(test_string)"),d.append(""),d.append("for match_num, match in enumerate(matches, start=1):",4),d.append(`print(f"${e}: {match.group()}")`)):(e=(0,x.Ay)("Match was found at {1}","{match.start()}-{match.end()}"),t=(0,x.Ay)("Group {1} found at {2}","{group_num}","{match.start(group_num)}-{match.end(group_num)}"),d.append("match = pattern.search(test_string)"),d.append(""),d.append("if match is not None:",4),d.append(`print(f"${e}: {match.group()}")`)),d.append(""),d.append("for group_num, group in enumerate(match.groups(), start=1):",8),d.append(`print(f"${t}: {group}")`,0)}return(0,A.jsx)(R,{lang:"py",children:d.toString()})},ue=(0,r.memo)(le);_("ruby",n(10092).A);const ce=e=>{const t=e.regex,n=e.flags,a=e.testString,r=e.isSubstituting,s=e.substString,p=e.isGlobal,i=new $,d=n.replace(/[^ixmo]/g,"");return i.append("re = /"+W(t,"/")+"/"+d),i.append(`str = '${X(a,"\\","'")}'`),r?(i.append(`subst = '${X(s,"\\","'")}'`),i.append(""),i.append("result = str."+(p?"g":"")+"sub(re, subst)"),i.append(""),i.append("# "+(0,x.Ay)("Print the result of the substitution")),i.append("puts result")):(i.append(""),i.append("# "+(0,x.Ay)("Print the match result")),p?(i.append("str.scan(re) do |match|",4),i.append("puts match.to_s",0),i.append("end")):(i.append("str.match(re) do |match|",4),i.append("puts match.to_s",0),i.append("end"))),(0,A.jsx)(R,{lang:"ruby",children:i.toString()})},ge=(0,r.memo)(ce);_("rust",n(11673).A);const he=e=>{const t=e.regex,n=e.flags,a=e.testString,r=e.isSubstituting,s=e.substString,p=e.isGlobal,i=new $,d=0===n.replace("g","").length?"":"(?"+n.replace(/[^imsUux]/g,"")+")",o=(t.match(/"#*/g)||[""]).reduce((e,t)=>e.length>t.length?e:t).length,l="#".repeat(o);return i.append("// "+(0,x.Ay)("include the latest version of the regex crate in your Cargo.toml")),i.append("extern crate regex;"),i.append(""),i.append("use regex::Regex;"),i.append(""),i.append("fn main() {",2),i.append(`let regex = Regex::new(r${l}"${d+t}"${l}).unwrap();`,2),i.append(`let string = "${X(a,"\\",'"')}";`),r?(i.append(`let substitution = "${X(s,"\\",'"')}";`),i.append(""),i.append("// "+(0,x.Ay)("result will be a String with the substituted value")),i.append("let result = regex.replace"+(p?"_all":"")+"(string, substitution);"),i.append(""),i.append('println!("{}", result);',0)):(i.append(""),p?i.append("// "+(0,x.Ay)("result will be an iterator over tuples containing the start and end indices for each match in the string")):i.append("// "+(0,x.Ay)("result will be a tuple containing the start and end indices for the first match in the string")),i.append("let result = regex.captures"+(p?"_iter":"")+"(string);"),i.append(""),p?(i.append("for mat in result {",4),i.append('println!("{:?}", mat);',2),i.append("}",0)):(i.append("let (start, end) = match result {",4),i.append("Some((s, e)) => (s, e),"),i.append("None => {",8),i.append("// ...",4),i.append("}",2),i.append("};"),i.append(""),i.append(""),i.append('println!("{}", &string[start, end]);',0))),i.append("}"),(0,A.jsx)(R,{lang:"rust",children:i.toString()})},me=(0,r.memo)(he);var fe=n(52540);const xe=e=>{switch(e.type){case"backreference":switch(e.kind){case"numeric":return null!=e.reference&&e.reference>=1&&e.reference<=9?`\\${e.reference}`:null;case"named":case"relative":return null}case"text-insertion":switch(e.kind){case"full-match":return"&";case"highest-group":case"precedes-match":case"follows-match":case"input-string":case"regex-mark":case"last-group":return null}case"text":return be(e.codePoint??e.charCode);case"text-escape":return null==e.charCode?null:be(e.charCode);case"case-modifier":return e.string;case"group":return null}},be=e=>{switch(e){case 0:return"\\x00";case 7:return"\\a";case 8:return"\\x08";case 9:return"\\t";case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";case 27:return"\\x1b";case 38:return"\\&";case 92:return"\\\\";default:return String.fromCodePoint(e)}},Se=e=>(0,A.jsx)(R,{lang:"common",children:$e(e)}),$e=e=>
1{const t=e.regex,n=e.flags,a=e.flavor,r=e.testString,s=e.isSubstituting,p=new $;if(s){const s=X(t,"/"),i=(({regex:e,flags:t,flavor:n,delimiter:a,substString:r})=>{const s=(0,I.rG)(e,{delimiter:a,flags:t,flavor:n,invalidFlagsBehavior:"sanitize"}).state,p=(0,I.tk)(r,(0,fe.b)({flags:t,flavor:n,captureGroupCount:s.status.captureGroupCount,subpatternNames:s.tables.subpatternNames})),i=p.tokens;if(p.patternError)return null;let d="";for(const e of i){const t=xe(e);if(null==t)return null;d+=t}return d})(e);if(p.append("# If you'd like to omit non-matching lines from the result; add ';d' to the end of the expression."),null==i)return p.append("# This Boost.Regex replacement uses constructs that sed cannot represent."),p.toString();n.includes("s")&&p.append("# sed has no direct equivalent for the dotall flag; it is omitted."),n.includes("m")||p.append("# sed processes input one line at a time, so non-multiline anchors may behave differently.");const d=`s/${s}/${X(i,"/")}/${[...n].filter(e=>"g"===e||"i"===e).join("")};t`;p.append(`sed${a===I.oI.POSIX_BRE?"":" -E"} ${Y(d)} <<< ${Y(r)}`)}else p.append((0,x.Ay)("This generator only supports substitution. Please update your regular expression accordingly"));return p.toString()},ye=(0,r.memo)(Se);_("swift",n(68176).A);const Ae=(e="")=>{const t=/\n/.test(e),n=(e.match(/#+/g)||[]).reduce((e,t)=>t.length>e?t.length:e,0),a="#".repeat(n+1);let r=a;return r+=t?'"""\n':'"',r+=e,r+=t?'\n"""':'"',r+=a,r},Re=e=>{const t=e.regex,n=e.flags,a=e.testString,r=e.isSubstituting,s=e.substString,p=e.isGlobal,i=new $,d=[],o=n.replace(/[gmixs]/g,"");n.includes("m")&&d.push(".anchorsMatchLines"),n.includes("i")&&d.push(".caseInsensitive"),n.includes("x")&&d.push(".allowCommentsAndWhitespace"),n.includes("s")&&d.push(".dotMatchesLineSeparators");let l="";return 1===d.length?(l+=", options: ",l+=d[0]):d.length>1&&(l+=", options: [",l+=d.join(", "),l+="]"),i.append("import Foundation"),i.append(),o.length>0&&(o.indexOf("X")>-1&&(i.append("// WARNING: You included a flag that Swift doesn't support: X"),i.append("//          When this flag is set, it causes any backslash in the pattern that is followed by a letter that has no special meaning to cause an error."),i.append("//          By default in Swift, a backslash followed by a letter with no special meaning will be treated as a literal.")),o.indexOf("u")>-1&&(i.append("// WARNING: You included a flag that Swift doesn't support: u"),i.append("//          When this flag is set, it makes the pattern and subject strings to be treated as unicode."),i.append("//          Swift already treats the pattern and subject strings as unicode by default, so including this flag is redundant.")),o.indexOf("J")>-1&&(i.append("// WARNING: You included a flag that Swift doesn't support: J"),i.append("//          Wehn this flag is set, it allows duplicated capturing group names."),i.append("//          By default, Swift captures only the last value matched for a repeated capture group."),i.append("//          As an alternative, the pattern can be modified to contain one capturing group per group you want to get in the result.")),o.indexOf("A")>-1&&(i.append("// WARNING: You included a flag that Swift doesn't support: A"),i.append('//          When this flag is set, it causes the pattern to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string").'),i.append("//          As an alternative, this effect can also be achieved by appropriate constructs in the pattern itself.")),o.indexOf("U")>-1&&(i.append("// WARNING: You included a flag that Swift doesn't support: U"),i.append("//          When this flag is set, it inverts the \"greediness\" of the quantifiers so that they are not greedy by default, but become greedy if followed by '?'."),i.append("//          As an alternative, this effect can also be achieved by setting a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).")),o.indexOf("D")>-1&&(i.append("// WARNING: You included a flag that Swift doesn't support: D"),i.append("//          When this flag is set, it forces the a dollar sign ('$'), to always match end of the string, instead of end of the line. This option is ignored if the 'm' flag is set."),i.append("//          There's no equivalent implementation of this flag in Swift, but you may want to check the 'm' flag instead.")),i.append()),i.append(`let pattern = ${Ae(t.toString())}`),i.append(`let regex = try! NSRegularExpression(pattern: pattern${l})`),i.append(`let testString = ${Ae(a)}`),i.append("let stringRange = NSRange(location: 0, length: testString.utf16.count)"),r?(i.append(`let substitutionString = ${Ae(s)}`),p?(i.append("let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)"),i.append("print(result)")):(i.append("let lookupRange = (testString as NSString).range(of: pattern, options: .regularExpression, range: stringRange)"),i.append("if lookupRange.intersection(stringRange) != nil {",4),i.append("let result = regex.stringByReplacingMatches(in: testString, range: lookupRange, withTemplate: substitutionString)"),i.append("print(result)",0),i.append("} else {",4),i.append('print("No matches were found.")',0),i.append("}"))):p?(i.append("let matches = regex.matches(in: testString, range: stringRange)"),i.append("var result: [[String]] = []"),i.append("for match in matches {",4),i.append("var groups: [String] = []"),i.append("for rangeIndex in 1 ..< match.numberOfRanges {",8),i.append("let nsRange = match.range(at: rangeIndex)"),i.append("guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }"),i.append("let string = (testString as NSString).substring(with: nsRange)"),i.append("groups.append(string)",4),i.append("}"),i.append("if !groups.isEmpty {",8),i.append("result.append(groups)",4),i.append("}",0),i.append("}"),i.append("print(result)")):(i.append("if let firstMatch = regex.firstMatch(in: testString, range: stringRange) {",4),i.append("let result: [String] = (1 ..< firstMatch.numberOfRanges).map { (testString as NSString).substring(with: firstMatch.range(at: $0)) }"),i.append("print(result)",0),i.append("} else {",4),i.append('print("No matches were found.")',0),i.append("}")),(0,A.jsx)(R,{lang:"swift",children:i.toString()})},_e=(0,r.memo)(Re),ve=["language"],we=e=>{let t=e.language,n=(0,b.A)(e,ve);const a=(e=>{switch(e){case ne.Ay.JAVASCRIPT:return te;case ne.Ay.PHP:return pe;case ne.Ay.PYTHON:return ue;case ne.Ay.CSHARP:return U;case ne.Ay.CPP:return G;case ne.Ay.CPP_STD_REGEX:return M;case ne.Ay.JAVA:return K;
1case ne.Ay.RUBY:return ge;case ne.Ay.RUST:return me;case ne.Ay.GOLANG:return V;case ne.Ay.GREP:return J;case ne.Ay.PERL:return re;case ne.Ay.AUTOIT:return E;case ne.Ay.SED:return ye;case ne.Ay.SWIFT5_2:return _e;default:throw new Error(`Unknown language '${e}`)}})(t);return(0,A.jsx)(a,Object.assign({},n))},Ee=()=>{const e=(0,f.GV)(e=>e.regexEditor.regex),t=(0,f.GV)(e=>e.regexEditor.flags),n=(0,f.GV)(e=>e.regexEditor.delimiter),b=(0,f.GV)(e=>{var t;return(null==(t=(0,h.Cr)(e))?void 0:t.value)??""}),S=(0,f.GV)(e=>e.regexEditor.substString),$=(0,f.GV)(e=>e.regexEditor.flavor),y=(0,f.GV)(e=>e.settings.defaultCodeGenLanguage),R=(0,r.useRef)(null),_=(0,m.w)().editorMode===i.lX.SUBSTITUTION,v=y||(0,ne._d)($,_),w=(0,r.useState)(null),E=(0,a.A)(w,2),I=E[0],C=E[1],P=I??v,N=ne.q5.find(e=>e.value===P)||ne.q5[0];return(0,A.jsxs)(d.B,{tool:"code-generator",title:(0,x.Ay)("Code Generator"),helpUrl:g.JZ,bodyClassName:"CDnGT",selection:(0,A.jsx)(u.G,{variant:"white-ghost","aria-label":(0,x.Ay)("Language"),searchPlaceholder:(0,x.Ay)("Search languages..."),emptyText:(0,x.Ay)("No languages match your search."),options:ne.q5.map(e=>({value:e.value,label:e.string})),value:N.value,onValueChange:C}),actions:(0,A.jsx)(c.i8,{variant:"white-ghost",getCopyComponent:()=>R.current,text:(0,x.Ay)("Copy code")}),children:[(0,A.jsx)("div",{className:"XCARr",ref:R,children:(0,A.jsx)(we,{regex:e,flags:t,delimiter:n,testString:b,isSubstituting:_,substString:S,flavor:$,isGlobal:t.includes("g"),language:N.value})}),(0,A.jsxs)("footer",{className:"eWBQp",children:[(0,A.jsx)(c.WV,{tag:"p",text:"Review generated code before using it. {1}",ph1:(0,A.jsx)(c.N_,{to:N.referencePage,absolute:!0,target:"_blank",withExternalIcon:!0,children:(0,x.Ay)("{1} regex reference",N.string)})}),(0,A.jsx)(p.z,{handle:o.CL,payload:l.L.editorOutput,className:"AExpx",render:(0,A.jsx)(c.$n,{variant:"text",text:(0,x.Ay)("Code generator settings"),icon:s.xPd})})]})]})}},14603(e,t,n){n.d(t,{B:()=>c});var a=n(53373),r=n.n(a),s=n(75391),p=n(97762),i=n(14202),d=n(46821),o=n(56646),l=n(84574),u=n(31085);const c=({title:e,tool:t,helpUrl:n,children:a,className:c,bodyClassName:g,selection:h,actions:m})=>(0,u.jsxs)(p.h,{fullBleed:!0,className:r()("_buCb",c),children:[(0,u.jsxs)(i.c,{variant:"fullscreen",selection:h,actions:(0,u.jsxs)(u.Fragment,{children:[m,(0,u.jsx)(d.v,{text:(0,l.Ay)("Help"),variant:"white-ghost",to:n,onClick:()=>(0,o.s)("docs.clicked",{topic:t}),target:"_blank",absolute:!0})]}),children:[e,null!=h&&":"]}),(0,u.jsx)(s.R,{className:r()("MNnpW",g),children:a})]})}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.