-1

例如:

specified_character = "你好啊"
str_to_replace1 = "你好啊朋友"
str_to_replace2 = "你好啊"

我想要一个正则表达式来匹配整个specified_character. 它说只有str_to_replace2会匹配。我目前有:

/(?<=[^\p{Han}])#{specified_character}(?=[^\p{Han}])/

结果:

str_to_replace1 = "你好啊朋友"
str_to_replace2 = "new text"
4

2 回答 2

1

您需要在 start(^) 和 end($) 中添加一个锚点

pattern = /^Apple$/
'Apple'.gsub(pattern, 'Orange') # => 'Orange'
'Apple Pie'.gsub(pattern, 'Orange') # => 'Apple Pie'
于 2013-03-05T04:32:20.443 回答
0

如果您想查看字符串是否与模式相同,那么您根本不应该使用正则表达式。只需使用字符串比较==

specified_character = "你好啊"
str_to_replace1 = "你好啊朋友"
str_to_replace2 = "你好啊"

str_to_replace1 == specified_character # => false
str_to_replace2 == specified_character # => true
于 2013-03-05T08:05:43.217 回答