[英]Using regex in filter in Julia
It is possible to filter items that fits a simple condition to match strings in Julia:可以过滤符合简单条件的项目以匹配 Julia 中的字符串:
y = ["1 123","2512","31 12","1225"]
filter(x-> ' ' in x, y)
[out]: [出去]:
2-element Array{String,1}:
"1 123"
"31 12"
But how do I get the reverse where I want to keep the items that doesn't match the condition in a filter?但是,如何将与条件不匹配的项目保留在过滤器中?
This syntax isn't right:这种语法不正确:
> y = ["1 123","2512","31 12","1225"]
> filter(x-> !' ' in x, y)
MethodError: no method matching !(::Char)
Closest candidates are:
!(::Bool) at bool.jl:16
!(::BitArray{N}) at bitarray.jl:1036
!(::AbstractArray{Bool,N}) at arraymath.jl:30
...
in filter(::##93#94, ::Array{String,1}) at ./array.jl:1408
Neither is such Python-like one:也不是这样的 Python:
> y = ["1 123","2512","31 12","1225"]
> filter(x-> ' ' not in x, y)
syntax: missing comma or ) in argument list
Additionally, I've also tried to use a regex:此外,我还尝试使用正则表达式:
> y = ["1 123","2512","31 12","1225"]
> filter(x-> match(r"[\s]", x), y)
TypeError: non-boolean (RegexMatch) used in boolean context
in filter(::##95#96, ::Array{String,1}) at ./array.jl:1408
Beyond checking whether a whitespace is in string, how can I use the match()
with a regex to filter out items from a list of strings?除了检查字符串中是否有空格之外,我如何使用带有正则表达式的
match()
来过滤字符串列表中的项目?
In order:为了:
filter(x-> !' ' in x, y)
. filter(x-> !' ' in x, y)
。 The precedence is wrong here.这里的优先级是错误的。 The error message is telling you that it's trying to apply the
!
错误消息告诉您它正在尝试应用
!
function to a single Char
argument: (!' ') in x
.函数到单个
Char
参数: (!' ') in x
。 You need explicit parentheses:您需要明确的括号:
julia> filter(x-> !(' ' in x), y) 2-element Array{String,1}: "2512" "1225"
filter(x-> ' ' not in x, y)
. filter(x-> ' ' not in x, y)
。 not
isn't a keyword in Julia. not
不是 Julia 中的关键字。
filter(x-> match(r"[\\s]", x), y)
. filter(x-> match(r"[\\s]", x), y)
。 The error is telling you that it expected a boolean value but didn't get one.错误告诉你它期望一个布尔值但没有得到一个。 Unlike Python, Julia doesn't have "truthy" values.
与 Python 不同,Julia 没有“真实”值。 So instead of
match
, use contains
.因此,不要使用
match
,而使用contains
。
julia> filter(!contains(r"[\\s]"), y) 2-element Vector{String}: "2512" "1225"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.