3

Say I have a string in Perl I am trying to match and replace with stuff:

$string =~ s/[^a-zA-Z]$find[^a-zA-Z]/$replace/g;

So as shown, I want to replace everything that is surrounded on both sides by nonletter characters. However, when I replace the string, I do NOT want to also replace these characters: they are just necessary for correct matching. How can I tell the Perl regex to avoid replacing the things surrounding $find?

3
  • Do you want to locate text that is sandwiched between non-alphabetic characters? Or do you want to match a pattern but excluding alphabetic characters? The two tests are not the same at the beginning or end of the string. Commented Nov 10, 2015 at 22:46
  • My intent was to do the first of the two. Both sln's and hjpotter92's answers accomplish this, not sure about ergonaut's. Commented Nov 10, 2015 at 23:41
  • Also have a look at \b. Commented Nov 11, 2015 at 9:06

2 Answers 2

4

Use perl lookaround assertions.

s/(?<=[^a-zA-Z])$find(?=[^a-zA-Z])/$replace/g
Sign up to request clarification or add additional context in comments.

Comments

4

Store them as a matched group, and reference them in the replacement string:

$string =~ s/([^a-z])$find([^A-Z])/\1$replace\2/gi;

1 Comment

Although using \1 and \2 on the RHS of a substitution works, perldoc perlre calls it "a dirty habit to get into." You should use $1 and $2 instead.

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.