Reputation: 2367
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
Reputation: 26667
Look behinds will be helpful in such situations
The regex can look like:
/(?<!.{50})123/
123
is not preceded by 50
charactersUsage
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