正则表达式实现内容定位与跨位置替换需求咨询
\type{...} Content into type="" Attribute Got it, let's solve this regex replacement task together. You've already started matching the relevant parts, now we just need to combine those pieces into a single pattern that captures the value we need and places it exactly where it belongs.
Step 1: The Find Pattern
We'll use a regex that captures key segments of your string to rearrange later. Here's the pattern:
(<parameter[^>]*type=")(".*?>)\\type{([^}]*)}(.*)
Let's break down each component:
(<parameter[^>]*type="): Capture Group 1 – grabs everything from the start of the<parameter>tag up to the opening quote of the emptytypeattribute.": Matches the closing quote of the emptytypeattribute (we don't capture this because we're replacing its position with our extracted value).(.*?>): Capture Group 2 – captures the rest of the<parameter>tag from the closing quote to the tag's end (>). The.*?is a non-greedy match to avoid overshooting into unrelated content.\\type{: Matches the literal\type{(we escape the backslash with another backslash since it’s a special regex character).([^}]*): Capture Group 3 – grabs the value inside the curly braces (likeINTin your example) by matching any character except}.}(.*): Capture Group 4 – captures the closing}and everything that comes after it in the string.
Step 2: The Replacement String
Now we’ll rearrange the captured groups to plug the extracted value into the empty type attribute. Use this replacement string:
$1$3$2$4
Here's what each part does:
$1: Puts back the first captured group (<parameter ... type=").$3: Inserts the value we extracted from\type{...}(likeINT).$2: Adds back the rest of the<parameter>tag (from the closing quote to>).$4: Appends the remaining content of the string (minus the original\type{INT}part, which we’ve moved).
Example Result
Applying this to your sample string:
Original:
<parameter name="some name" value="VALU" type="" perm="" ncpv="1"><doc></doc></parameter> \type{INT}\ro some documentation
After replacement:
<parameter name="some name" value="VALU" type="INT" perm="" ncpv="1"><doc></doc></parameter> \ro some documentation
Optional: Keep the Original \type{INT}
If you want to copy the value instead of moving it (leaving \type{INT} in the string), use this replacement string instead:
$1$3$2\\type{$3}$4
This will retain the original \type{INT} while still filling the type attribute with the same value.
内容的提问来源于stack exchange,提问作者user3270371

