[英]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 . 假设我有一个字符串
s
,我想用"abcd"
替换所有"123"
, 但只能在前50个字符中 。
I know can do 我知道可以
s[0,50] = s[0,50].gsub("123", "abcd")
But is there a way to do it directly on s
? 但有没有办法直接在
s
上做?
Look behinds will be helpful in such situations 在这种情况下,看后面会有所帮助
The regex can look like: 正则表达式可能如下所示:
/(?<!.{50})123/
123
is not preceded by 50
characters 123
之前没有50
字符 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.