例如:
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"
答案 0 :(得分:1)
您需要添加一个锚点来开始(^)和结束($)
pattern = /^Apple$/
'Apple'.gsub(pattern, 'Orange') # => 'Orange'
'Apple Pie'.gsub(pattern, 'Orange') # => 'Apple Pie'
答案 1 :(得分:0)
如果您想查看字符串是否与模式相同,那么您根本不应该使用正则表达式。只需使用字符串比较==
。
specified_character = "你好啊"
str_to_replace1 = "你好啊朋友"
str_to_replace2 = "你好啊"
str_to_replace1 == specified_character # => false
str_to_replace2 == specified_character # => true