首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字符串替换为regexp

字符串替换为regexp
EN

Stack Overflow用户
提问于 2012-01-23 21:39:09
回答 1查看 202关注 0票数 1

我有一个regexp设置$1 :它对应于()在:the_beginning(.*)the_end中的文本。

我想用somethingelse替换与$1对应的值,而不是所有regexp。

实际上下文中的:

my_string包含:

/* MyKey */ = { [code_missing]; MY_VALUE = "123456789"; [code_missing]; }

我想把"123456789“替换为"987654321”(例如)。这是我的雷杰普:

"/\\* MyKey \\*/ = {[^}]*MY_VALUE = \"(.*)\";"

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-01-23 21:44:59

我仍然不确定你到底想要什么,但以下是一些应该能帮助你的代码:

代码语言:javascript
复制
str = "Hello this is the_beginning that comes before the_end of the string"
p str.sub /the_beginning(.+?)the_end/, 'new_beginning\1new_end'
#=> "Hello this is new_beginning that comes before new_end of the string"

p str.sub /(the_beginning).+?(the_end)/, '\1new middle\2'
#=> "Hello this is the_beginningnew middlethe_end of the string"

编辑:

代码语言:javascript
复制
theDoc = '/* MyKey */ = { [code_missing]; MY_VALUE = "123456789";'
regex  = %r{/\* MyKey \*/ = {[^}]*MY_VALUE = "(.*)";}
p theDoc[ regex, 1 ]   # extract the captured group
#=> "123456789"

newDoc = theDoc.sub( regex, 'var foo = \1' )
#=> "var foo = 123456789"  # replace, saving the captured information

编辑#2:在匹配之前/之后访问信息的

代码语言:javascript
复制
regex = /\d+/
match = regex.match( theDoc )
p match.pre_match, match[0], match.post_match
#=> "/* MyKey */ = { [code_missing]; MY_VALUE = \""
#=> "123456789"
#=> "\";"

newDoc = "#{match.pre_match}HELLO#{match.post_match}"
#=> "/* MyKey */ = { [code_missing]; MY_VALUE = \"HELLO\";"

请注意,这需要一个与前/后文本不匹配的正则表达式。

如果需要指定限制,而不是内容,则可以使用零宽度查找/提前查找:

代码语言:javascript
复制
regex = /(?<=the_beginning).+?(?=the_end)/
m = regex.match(str)
"#{m.pre_match}--new middle--#{m.post_match}"
#=> "Hello this is the_beginning--new middle--the_end of the string"

…但现在,这显然不仅仅是捕获和使用\1\2。我不确定我完全明白你在寻找什么,为什么你认为这会更容易。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8978981

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档