Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
foreach and replace nested
#1
Hi,

I want to know the blue word section (powershell code) with the same effect as the QM code,

foreach and replace nested

Thanks in advance for any advice and help
david
________________________________________________________________________________
$s = @'
function A([Paragraph]$p1, [Paragraph]$p2){
    '{A}'
}
function BB([Paragraph]$p1){
    '{BB}'
}
function CCC(){
    '{CCC}'
}

function Main([string[]]$args)
{
    $A($p1, $p2)
    $BB($p1)
    $CCC()
}
'@

$b = $s | Select-String 'function ([a-zA-Z_][a-zA-Z0-9_]*\().*\)' -AllMatches |
foreach{
    $_.Matches |
    foreach{
        '${0}' -f $_.Groups[1].Value
    }
}


$s -split '\r?\n' |
foreach {
    foreach ($b_ in $b)
    {
        if ($_ -match [regex]::Escape($b_))
        {
            $_ = $_ -replace '\(', ' ' -replace '\)' -replace ',' -replace '^(\s*)\$','$1'
        }
    }
    $_
}
#2
The following code cannot be compiled

Macro Macro9
Code:
Copy      Help
str s=
;function A([Paragraph]$p1, [Paragraph]$p2){
;,'{A}'
;}
;function BB([Paragraph]$p1){
;,'{BB}'
;}
;function CCC(){
;,'{CCC}'
;}
;
;function Main([string[]]$args)
;{
;,$A($p1, $p2)
;,$BB($p1)
;,$CCC()
;}

str pattern="function ([a-zA-Z_][a-zA-Z0-9_]*\().*\)"
str d
ARRAY(str) a
findrx(s pattern 0 4 a)
for int'i 0 a.len
,d.addline(F"${a[1 i]}")

str e
foreach str's_ s
,foreach str'd_ d
,,if(findrx(s_ d_) != -1)
,,,s_.replacerx("(" " ")
,,,s_.replacerx("\" ",")
,,,s_.replacerx("^(\s)\$" "$1")
,e.addline(s_)

out e
#3
It fails at run time. Invalid regular expression.
#4
Still fails after escaping

        if(findrx(s_ d_.escape(1)) != -1)
#5
If need to escape whole string, don't use regular expression function.
Or use \Q \E.
F"\Q{d_}\E"
#6
succeed!

thank you so much!

Macro Macro9
Code:
Copy      Help
str s=
;function A([Paragraph]$p1, [Paragraph]$p2){
;,'{A}'
;}
;function BB([Paragraph]$p1){
;,'{BB}'
;}
;function CCC(){
;,'{CCC}'
;}
;
;function Main([string[]]$args)
;{
;,$A($p1, $p2)
;,$BB($p1)
;,$CCC()
;}

str pattern="function ([a-zA-Z_][a-zA-Z0-9_]*\().*\)"
str d
ARRAY(str) a
findrx(s pattern 0 4 a)
for int'i 0 a.len
,d.addline(F"${a[1 i]}")

str e
foreach str's_ s
,foreach str'd_ d
,,if(findrx(s_ F"\Q{d_}\E") != -1)
,,,s_.replacerx("\(" " ")
,,,s_.replacerx("\)" "")
,,,s_.replacerx("," "")
,,,s_.replacerx("^(\s)\$" "$1")
,e.addline(s_)

out e

QM is very legendary, very classic  Smile
With LA, there may be more code


Forum Jump:


Users browsing this thread: 1 Guest(s)