Jump to content
kerim

How to insert a new line in a RegEx search and replace?

Recommended Posts

The right-hand box doesn't support regexes (beyond $1 etc. references to match groups). You'll probably have to use a Run Script box and do it in code.

Share this post


Link to post

Some research tells me that Perl is a good scripting language to do this in, and I can find examples online, but I don't know how to work them into the right format for use with Alfred Workflows. This is what I have now, but it isn't working... (trying to replace "apple" with "pear" as a test)

 

$query = "{query}";

-p -e 's/apple/pear/g;' $query

print $query;

 

Share this post


Link to post

Found an example that made more sense to me. This works!

 

$query = "{query}";

my $find = "apple";
my $replace = "pear";
$find = quotemeta $find; # escape regex metachars if present

$query =~ s/$find/$replace/g;

print $query;

 

 

Share this post


Link to post

While that worked on a single line, I needed to change /g to /gm to do mult-line search. Then I needed to remove the "escape regex" line to be able to use more complex search operators. I also found that certain perl regex operators didn't seem to work for me. For instance instead of

^\s{4}-

 I had to enter

 

^    -

(with actual spaces).

 

I don't know why? I tested the above syntax on some online regex testing sites and it worked...

Share this post


Link to post

If you don't already know Perl, I'd recommend you use Ruby or Python or PHP or JavaScript. Basically, anything but Perl.

 

Almost nobody on the forum uses Perl, so you won't get much, if any, help.

 

What exactly are you trying to achieve?

Share this post


Link to post

If it helps, Alfred's 'Replace' workflow utility object can actually accept new lines if you alt-enter in the right field.

 

It's likely at some point I'll take a fresh look at all of the utility objects to see how they can be improved :)

 

Cheers,

Andrew

Share this post


Link to post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...