Replace all regular expression matches in a string

Given the string:

This is_ an_example.

I want to produce:

This - is - an example.

IOW, replace all instances of ‘\s*_\s*’ with ’ - ’ (note the spaces on each side of the dash). Can this be done via rreplace? (Preferably in one call.) As far as I can tell, the standard regex ‘g’ operator for replacing all matches (e.g. ‘s/abc/def/g’) doesn’t work.

Ultimately I want to replace all of a set of certain characters in album and track names with ’ - ', but that just means using a group like ‘[\/;_]’ in place of merely ‘_’.

(To keep the strings simple here, I didn’t escape with ‘\’. Naturally I’ll do that in the real script.)

Thanks!

Replacing all occurrences is the default behaviour in $rreplace. Just use a group like this:

$set(title,$rreplace(%title%,[abc],-))

It will replace all occurrences of a, b and c with a -. Of course use the characters you actually want to replace.

One important note: Your example of replacing _ makes me wonder, if you actually saw Picard generating underscores in filenames and you want to get rid of that. If so, you have to replace the actual characters getting replaced with _ by Picard in your script (if Windows compatible filenames is activated, Picard will replace ["*:<>?|] with an underscore).

Also note that Picard will always replace / and \ with an underscore before applying the script, as those characters are used as directory separators (and you don’t want to have AC/DC end up in two folders).

I’m seeing the problem in the Options/File Renaming pane. The second example seems to be impervious to replacing one of the underscores. But if I need to be looking for the original characters that the underscores have replaced, then it’s a matter of knowing what those are.

MB automatically replaces characters that the OS doesn’t accept in file names, but there are others I also want to replace and some of the chars that MB replaces I’d rather replace with other than underscores. (One might argue that I’m a little OCD about my filenames. One would be correct.)

I’ll try the Windows list of unacceptable filename chars and see how it goes.

This works for the example in Options:

$set(_album,$rreplace(%album%,\(\\s*[/\\<>*:;?_"|]+\\s*\), - ))

I’l use it until it breaks, then figure that out. I’ve been designing and writing software for over 30 years, so I’m used to that. :wink:

1 Like