我试图编写一个Julia函数,该函数使用正则表达式对字符串数组中的每个元素执行查找和替换操作。它本质上是一个广播replace()
调用的包装器。如果您熟悉R的字符串包,则此函数的工作方式与stringr::str_replace_all()
大致相同。
下面的代码将“EE”的所有实例替换为“EE”,将“问候”替换为"grEEtings":
arr = ["hi", "hello", "welcome", "greetings"]
replace.(arr, r"e{2}" => "EE")
我编写的函数不返回对arr
中值的修改。
function str_replace_all(string::String, pattern::String, replacement::String)
replace.(string, Regex(pattern) => replacement)
end
str_replace_all(arr, "e{2}", "EE")
哪里出了问题?谢谢!
发布于 2022-03-20 06:19:35
在您的函数中删除类型注释,它应该可以工作:
julia> arr = ["hi", "hello", "welcome", "greetings"]
julia> function str_replace_all(string, pattern, replacement)
replace.(string, Regex(pattern) => replacement)
end
https://stackoverflow.com/questions/71543949
复制相似问题