Re: [FishMonger] Can I do an if-then-else regex mixing match and substitution?
[In reply to]

Can't Post

Yes, I believe those if-then-else conditionals. But it appears, and I could be wrong, that it applies for match regex, not any other type of regex. I want to integrate both match and substitution regex with these conditionals.

see this link: http://www.regular-expressions.info/conditional.html

Normally, I believe it's just "if" this matches, "then" check if that matches, "else" check if yet-another-thing matches.

I have a text file, right.

Code

Hello World

Foo Bar

I want to do a search..match on 'Foo'. If it finds 'Foo' in this file, then do a search..replace on 'Hello World'. If it finds 'Hello World', then substitute 'Hello World' for 'Hello Earth'. You see what I mean? If 'Foo' was not present in this text file, it wouldn't even bother looking for 'Hello World'.

Could I do this in a script like Perl? Sure, I could. But I understand Regex provides some sort of condtional functionality and I thought why not just use regex if it has this feature.

Re: [FishMonger] Can I do an if-then-else regex mixing match and substitution?
[In reply to]

Can't Post

Thank you for the suggestions.

miller's suggestion is pretty much what I was trying to accomplish.

However, I am executing this in in-place edit mode in a batch file and it's failing on the vertical bar character in my regex:

Code

if (m~[\'|\"]\d{1,2}[\'|\"]~i)...

The error is "The system cannot find the path specified."

I realize that I don't need the vertical bar character, in this case, but if I do in the future, this could be an issue. Now, I tried modifying it a couple of different ways to narrow in on the problem.

These work:

Code

if (m~[\'\"]\d{1,2}[\'\"]~i)...

Code

if (m~[\'|\"]\d{1,2}[\'\"]~i)...

This does not:

Code

if (m~[\'\"]\d{1,2}[\'|\"]~i)...

I tried escaping the vertical bar but I got the same error:

Code

if (m~[\'\"]\d{1,2}[\'\|\"]~i)...

Does anybody know what's the problem?

Update: I did manage to find the solution. The problem is I had to precede the vertical bar with the caret (^) symbol and now it enters the if loop, due to the fact that i'm executing a Perl script inside a batch file.

I also discovered that doing a match, followed by a substitution using in-place edit mode won't replace in the file. I think this is also due to the batch process. FYI, I'm using

Code

for %%X in (*.txt) do perl -pi.bak -e "Perl code" %%X

What I'm wondering is is it possible to use look-ahead or look-behind assertions in substitutions or are assertions for matching only? Either way, it appears that in-place edit won't work here and I'll have to follow your suggestions to a T, running separate perl script.