r/PowerShell • • Oct 26 '26

Question Beginner looking for help in a sea of Regex

So I discovered how useful Powershell is about 3 weeks ago and have been playing with it and tweaking my PC with all manner of useless changes. I have reached something that has left me rather stumped even after a fair bit of Googling (AI results disclosure?) and several hundred changes of my 'script'. Posting here is probably like whacking a mole with a warhead but hey why not!

I have been attempting to change a subtitle file with several thousands of lines of text, they all follow the following pattern:

Dialogue: 0,0:00:12.92,0:00:17.34,Default,,0000,0000,0000,,{\pos(540*,420)}Hello world!\N*

I would like to add 140 to all of the first numbers after "{\pos(" (e.g 540 becomes 680.)

Dialogue: 0,0:00:12.92,0:00:17.34,Default,,0000,0000,0000,,{\pos(680*,420)}Hello world!\N*

I have been attempting to do this by loading the .ass text file in (this'll be part of a batch file so I am calling Powershell from CMD), then using the -replace function as follows:

powershell -Command "((Get-Content -path <path to sub.ass> -Raw) -replace '\{\\pos\(\d+,','\{\pos\(${140 + \d+},') | Set-Content -Path <path to sub.ass>"

However this results in the following results for all lines of dialogue:

Dialogue: 0,0:00:12.92,0:00:17.34,Default,,0000,0000,0000,,\{\pos\(,420)}Hello world!\N

This is one of the more promising results where {140 + \d+} simply vanished. Without the $ in front of {140 + \d+} Powershell will simply repeat whatever code I put into into it back at me in place of \d+ like so: {\pos\({140 + \d+},420)}

I suspect that because I am attempting to isolate a number by using the surrounding punctuation the program is reading \d+ as a string rather than an integer.

TLDR: I am attempting to increase the value of the same integer on every line of text by 140 using \d+. \d+ could be any number from 0 to 1540. Not using \d+ is fine but I have no idea what other options are available.

Pointing me in the direction of what I should learn to get this to work could also be great as this is actually a pretty enjoyable program - I just think I went a little too deep too fast with this one.

10 Upvotes

24 comments sorted by

4

u/Scylenthum Oct 26 '26

I posted this last night before heading to bed and my goodness I am blown away by these responses! I have to go to work, but once I get some free time tonight I will be going over these and seeing how you all got to these methods. Some of these are are for sure more like black magic to me, but I shall try and wrap my head around them. So replies will be incoming!

Once again, thanks everyone!!!

10

u/x0n Oct 26 '26 edited Oct 26 '26 • Galaxy Brain

Assuming:

$s = "Dialogue: 0,0:00:12.92,0:00:17.34,Default,,0000,0000,0000,,{\pos(540*,420)}Hello world!\N*"

We want to replace n with n+140 only where it is preceded by the string "\pos("

[regex]::replace($s, "(?<=\\pos\()(\d+)", { param($match); [int]$match.value + 140 })

results in:

Dialogue: 0,0:00:12.92,0:00:17.34,Default,,0000,0000,0000,,{\pos(680*,420)}Hello world!\N*

This is done by using a "positive look-behind assertion", i.e. there IS something behind the target match that matches a pattern, and then the normal capture of the number. We are then using the dotnet MatchEvaluator overload of Regex.Replace, and powershell will handle creating a delegate for it and bind to a scriptblock. Note that I have to cast the value to [int] to ensure addition doesn't become a string concatenation.

6

u/surfingoldelephant Oct 26 '26

-replace can be used if it's PS v7:

$s -replace '(?<=\\pos\()(\d+)', { 140 + $_.Value }

Note that I have to cast the value to [int] to ensure addition doesn't become a string concatenation.

Or just place the integer literal on the left.

140 + $match.Value

3

u/CeleryMan20 Oct 26 '26 edited Oct 26 '26

… "positive look-behind assertion", … dotnet MatchEvaluator overload of Regex.Replace, …

Being unfamiliar with both of those, this feels like voodoo.

I’m struggling to understand why "\\pos\((\d+)" wouldn’t match. Off to do some reading and experimentation, I guess.

ETA: I would normally use a capture group to pull information out of a match, but lookbehind/look ahead exclude the extra anchoring part completely?

3

u/420GB Oct 26 '26

They are still using a capture group in their example code.

Lookbehinds and Lookaheads are useful because they do NOT match/consume any characters. They are like extra assertions, they do have to be fulfilled for the entire expression to match, but they themselves are only 0-length matches.

I personally find regex101.com to be the best site to test and learn.

2

u/ankokudaishogun Oct 26 '26 edited Oct 27 '26

EDIT: Disregard, I must have messed up something in my setup.

ORIGINAL: May I add a shorter version?
$s -replace "(?<=\\pos\()(\d+)", ([int]($Matches[1])+140)

Do note this only seems to work in Powershell 7+

The underlining mechanic is the same, 7+ just expanded the function of -replace to update the $Matches automatic variable.

1

u/surfingoldelephant Oct 27 '26 edited Oct 27 '26

-replace has no effect on $Matches, so that won't work as-is in any version.

You'd have to use -match/-notmatch first and repeat the regex, but that would be pointless:

if ($s -match '(?<=\\pos\()(\d+)') {
    $s -replace '(?<=\\pos\()(\d+)', (140 + $Matches[1])
} else {
    $s
}

Instead, you can use a script block delegate in PS 7 like I showed here and reference the match object using $_.

$s -replace '(?<=\\pos\()(\d+)', { 140 + $_.Value }

1

u/ankokudaishogun Oct 27 '26

Evidently I must have something messing up, as today I seem to not be able to replicate the effect. My bad, thank you for the correction.

4

u/sigil224 Oct 26 '26

I think I’d recommend trying not to do it in a single line but instead do it line by line (read data file and then foreach line in file…) then use regex to parse the line into named variables and manipulate values there and then recreate the line.
It’ll be slower but then you can debug line by line in your input file, try different things incrementally and see how it all works together.

1

u/x0n Oct 26 '26

Does nobody see I've already answered this? :)

7

u/sigil224 Oct 26 '26

I did and I think it’s good for beginners to get multiple options/alternatives. Also, gives people a way to learn further/adapt in future i.e if they decide they need to change two values in one line.
Options are always good!

3

u/BlackV Oct 26 '26 edited Oct 26 '26

x0n
Does nobody see I've already answered this? :)

You are indeed the leet hax0r for answering, very good

But, other people can answer too, it's allowed, and encouraged, as sometimes there are multiple ways to do things,more even better ways to do things

On top of that this person's suggestion of breaking it down to lines is actually good, when your are learning and testing and you can validate/test/fix as you go (instead of, for example, looking at the whole file each change you make)

Your particular answer said what the regex is doing, but didn't really break down how, op is struggling to understand regex, so an answer only solves part of the problem for them

3

u/purplemonkeymad Oct 26 '26

TLDR: I am attempting to increase the value of the same integer on every line of text by 140 using \d+. \d+ could be any number from 0 to 1540. Not using \d+ is fine but I have no idea what other options are available.

Pretty sure this is not something you can do only in regex.

You'll need to match the lines you want, put the value in a capture group to extract it, and either manually or via a second replace put in the new value.

I would recommend not to try to fit that into a single line.

2

u/cbass377 Oct 26 '26

I like to use this website to work up the actual regex. https://regexr.com/

You give it your text, then work on the regex operators until it is selecting what you want.

You will want to set it to PCRE mode.

There are 2 types of scripters, "Everything is a string" and "Everything is an Object" Powershell is for the object type of scripter. I came from Unix / Linux and early windows, building scripts in Perl, so I too am a string type. It is worth the discomfort of working with objects when you work in powershell. That said regex is a powerful tool to find what you want.

You may need to escape the "\" character and maybe the other two punctuation characters.

Hope this helps

3

u/CeleryMan20 Oct 26 '26

I’ll give regexr a try. My usual go-to is https://regex101.com

2

u/PlsChgMe Oct 26 '26

what a great comment!

1

u/thisisntwhatIsigned Oct 26 '26 edited Oct 26 '26

By treating everything as a string you miss out on the real power of powershell.

Can't check right now, but

 $List = Import-csv filename -delimiter "," 

Should import as a list of objects where you can the edit only that field in a foreach ($item in $list) loop with a much simpler $item.property -replace command.

-1

u/x0n Oct 26 '26

That doesn't address the problem at all. Even if you split by commas, you still end up with complex fields. And then exporting back to postscript (or whatever this is)? lol. No.

2

u/thisisntwhatIsigned Oct 26 '26

Only number in that field, much easier and safer expression. Super easy to convert to anything you want afterwards since it's all objects...

0

u/y_Sensei Oct 26 '26

Here's a broader approach that could be expanded to perform other replacement operations inside ASS files, too.
It is based on splitting the different ASS sections up, and processing each section separately, which could make sense since each such section has its own specific format.

$assIn = @'
[Script Info]
Title: Example ASS File
ScriptType: v4.00+
PlayResX: 1920
PlayResY: 1080
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,24,&H00FFFFFF,&H000000FF,&H00000000,&H64000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1
Style: Title,Arial,36,&H00FFFF00,&H000000FF,&H00000000,&H00000000,1,0,0,0,100,100,0,0,1,3,0,8,10,10,20,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:01.20,0:00:04.50,Title,,0,0,0,,Welcome to ASS Subtitles
Dialogue: 0,0:00:05.00,0:00:08.30,Default,,0,0,0,,This is regular dialogue text
Dialogue: 0,0:00:09.10,0:00:12.80,Default,,0,0,0,,{\i1}This text is italicized{\i0}
Dialogue: 0,0:00:13.50,0:00:16.20,Default,,0,0,0,,{\c&HFF0000&}This text is red{\c}
Dialogue: 0,0:00:17.00,0:00:20.40,Default,,0,0,0,,{\pos(960,540)}This text is centered
'@

<#
The following configuration options could (and should) of course be aggregated into another (configuration) object.
This simplified solution with 3 different variables just demonstrates the approach.
#>
$assDlgXOffsetMatchPattern = 'Dialogue: .*{\\pos\((?<xoval>\d+),\d+\)' # In order to be able to identify the value of interest, a named capture group is used
$assDlgXOffsetReplacePattern = "{\\pos\("
[Int]$assDlgXOffsetValue = 140 # Offset for X coordinates in ASS Dialogue entries

[System.Collections.Specialized.OrderedDictionary]$assDict = @{} # Dictionary to store ASS section names and their data as key/value pairs

# In order to have access to multiple regex matches, we use the .NET API (the PoSh functionality stops after the first match)
[RegEx]$pattern = '\[.*\]'
$result = $pattern.Match($assIn)

<#
Step 1:
For each match, add a corresponding key/value pair to the dictionary,
where a key denotes an ASS section name.
#>
while ($result.Success) {
  $assDict.Add($result.Value.Trim(), "")

  $result = $result.NextMatch()
}

<#
Step 2:
Assign the corresponding value to each dictionary entry.
Note that an approach like this only works with Dictionaries
whose entries can also be accessed by index (not just by key).
#>
$assSectVals = $assIn -split $pattern.ToString() | Where-Object -FilterScript { $_ -ne "" }

for ([Int]$i=0; $i -lt $assSectVals.Count; $i++) {
  $assDict[$i] = $assSectVals[$i]
}

<#
Step 3:
Iterate over the values of the extracted ASS [Events] section.
Each value which matches the configured offset value for X coordinates is being transformed accordingly.
#>
[System.Collections.Generic.List[String]]$assEvents = @()

$assDict."[Events]" -split "`r?`n" | ForEach-Object {
  if ($_ -match $assDlgXOffsetMatchPattern) {
    $assEvents.Add(($_ -replace ($assDlgXOffsetReplacePattern + $Matches.xoval), ($assDlgXOffsetReplacePattern + ($assDlgXOffsetValue + $Matches.xoval))))
  } else {
    $assEvents.Add($_)
  }
}

Write-Host $($assEvents -join "`r`n") # Display the result (the last line has been changed)

-3

u/OddAttention9557 Oct 26 '26

We don't bother trying to wrestle with regex any more, we just ask Claude; he speaks it natively while we lack suitable vocal equipment.