angus
angus

Reputation: 2367

gsub only in part of string

Let's say I have a string s and I want to replace all "123"'s with "abcd"'s, but only in the first 50 characters.

I know can do

s[0,50] = s[0,50].gsub("123", "abcd")

But is there a way to do it directly on s?

Upvotes: 1

Views: 265

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

Look behinds will be helpful in such situations

The regex can look like:

/(?<!.{50})123/
  • Negative look behind. Ensures that the 123 is not preceded by 50 characters

Regex Demo

Usage

string.gsub(/(?<!.{50})123/, "abc")

Test

print "1234567890123".gsub(/(?<!.{10})123/, "abc") # I was bit lazy that I                     
                                                   # checked only for 10 characters
=> abc4567890123

Upvotes: 3

Related Questions