正则表达式优化:提取INPUTBOX中带可选引号的string1与string2
Refined Regex for Extracting
<INPUTBOX> Values Alright, let's tweak that regex to cover all your requirements properly. Here's a refined solution that addresses the newline issue, supports multiple <INPUTBOX> instances, and enforces the colon-only-when-string2-exists rule:
/<INPUTBOX:(?|"[\n]?(.*?)"|([^:>]+))(?:\s*:\s*(?|"([^"]*)"|([^>]*)))?>/g
Breakdown of the Regex
Let's walk through each part to understand how it fixes your original issues:
<INPUTBOX:: Matches the fixed opening of your input box tag.(?|"[\n]?(.*?)"|([^:>]+)): A branch reset group that ensuresstring1lands in a consistent capture position, regardless of quotes:- First branch (
"[\n]?(.*?)"): Handles quotedstring1cases. The[\n]?skips any optional newline right after the opening quote, so it doesn't get included in the capturedstring1(exactly what you asked for). - Second branch (
([^:>]+)): Handles unquotedstring1cases, matching all characters until either a colon (ifstring2exists) or the closing>.
- First branch (
(?:\s*:\s*(?|"([^"]*)"|([^>]*)))?: An optional non-capturing group forstring2, which only triggers if a colon is present:\s*:\s*: Matches the colon, allowing optional whitespace (spaces, tabs, newlines) around it for flexibility.- Inner branch reset group (
(?|"([^"]*)"|([^>]*))): Capturesstring2in a consistent position, whether it's quoted (matches until the closing quote) or unquoted (matches until the closing>).
>: Matches the fixed closing of the input box tag./g: Global flag to match all<INPUTBOX>instances in a string, not just the first one.
Example Usage (JavaScript)
Here's how you can use this regex to extract values in practice:
const inputStr = ` Sample text with multiple inputs: <INPUTBOX:"\nHello World"> <INPUTBOX:foo:"bar baz"> <INPUTBOX:no-quotes:1234> `; const regex = /<INPUTBOX:(?|"[\n]?(.*?)"|([^:>]+))(?:\s*:\s*(?|"([^"]*)"|([^>]*)))?>/g; let match; while ((match = regex.exec(inputStr)) !== null) { const string1 = match[1] || match[2]; // Grab string1 from whichever branch captured it const string2 = match[3] || match[4]; // Grab string2 if it exists console.log(`String 1: "${string1}", String 2: ${string2 ? `"${string2}"` : "undefined"}`); }
Output:
String 1: "Hello World", String 2: undefined String 1: "foo", String 2: "bar baz" String 1: "no-quotes", String 2: "1234"
Notes
- This regex assumes quotes are unescaped (no
\"inside quoted values). If you need to support escaped quotes, we'd need to adjust the quoted branches to handle that, but it wasn't mentioned in your requirements. - The regex is case-sensitive as written. If you need case-insensitive matching for
<INPUTBOX>, add theiflag (e.g.,/.../gi).
内容的提问来源于stack exchange,提问作者Michael T
相关产品推荐
相关产品推荐

