0

I need to add a string in the middle of some sentences separated by \n. For Example:

INPUT          OUTPUT
V2+count    -> V2+came+count
V6+num      -> V6+came+num
V10+hi+town -> V10+came+hi+town

and

N2+hello    -> N2+went+hello
N7+time     -> N7+went+time

The code I wrote so far is

if ($new=~/\(came\)\|\(went\)/) {
    my $prev_tag = $`;
    if ($prev_tag5=~ /\(V\d+?\)?\+$/) {
        $new=~ s/\(came\)\|//;
    } else {
        $new=~s/\(went\)\|//;
    }
}
3
  • All your regular expressions include literal parenthesis, but the examples you have provided doe not include any parentheses, so they would not match any of your regexpes. Commented Sep 14, 2012 at 10:22
  • How should you choose between adding came or went in one specific case? Commented Sep 14, 2012 at 10:23
  • Are the + characters in your data (1) token delimiters — in fact you are working with a list of strings, or (2) whitespaces, you just wanted to emphasize them, or (3) literal plus + characters in the input/output? I am somewhat confused. Commented Sep 14, 2012 at 10:28

1 Answer 1

4

My advise is to keep it simple and not try to handle both cases in parallel. So start by adding 'came' to all the cases matching /V\d+/and then add 'went' to all the cases matching /N\d+/:

$new =~ s/(V\d+\+)/$1came+/;
$new =~ s/(N\d+\+)/$1went+/;
Sign up to request clarification or add additional context in comments.

2 Comments

Although it may be less readable, the two substitutions can be performed on one line using the r modifier: $new = $new =~ s/(V\d+\+)/$1came+/r =~ s/(N\d+\+)/$1went+/r;
More readable, but still one line: $new =~ s/(V\d+\+)/$1came+/;$new =~ s/(N\d+\+)/$1went+/;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.