我有一个内部包含字符的字符串,我只想匹配字符串周围的字符。
"This is a [1]test[/1] string. And [2]test[/2]"
红色 http://rubular.com/r/f2Xwe3zPzo
目前,链接中的代码与特殊字符中的文本匹配,我该如何更改?
更新
澄清我的问题。它应该只有在开盘和闭盘的数字相同时才匹配。
"[2]first[/2] [1]second[/2]"
在上面的代码中,只有第一个应该匹配,而不是第二个。应忽略特殊字符(第一个)内的文本。
最佳答案
试试这个:
(\[[0-9]\]).+?(\[\/[0-9]\])
Permalink以 Rubular 为例。
更新
既然你想删除“特殊”字符,试试这个:
foo = "This is a [1]test[/1] string. And [2]test[/2]"
foo.gsub /\[\/?\d\]/, ""
# => "This is a test string. And test"
更新,第二部分
您只想在周围的标签匹配时删除“特殊”字符,那么这个怎么样:
foo = "This is a [1]test[/1] string. And [2]test[/2], but not [3]test[/2]"
foo.gsub /(?:\[(?<number>\d)\])(?<content>.+?)(?:\[\/\k<number>\])/, '\k<content>'
# => "This is a test string. And test, but not [3]test[/2]"
关于ruby - 正则表达式匹配文本周围的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30200694/