Julia - 检查字符串中的每个字符是否为小写字母或空格

4
如何检查字符串中的每个字符是否为小写或空格?
"this is all lowercase"   -> true 
"THIS is Some uppercase " -> false 
"HelloWorld  "             -> false 
"hello world"              -> true

清晰的示例代码,用于解答问题。 - Julia Learner
3个回答

8
您可以使用all的谓词/itr方法(文档):
julia> f(s) = all(c->islower(c) | isspace(c), s);

julia> f("lower and space")
true

julia> f("mixED")
false

据我所知,islower 已经不存在多年了。新版本是 islowercase,但它的工作方式不同。islowercase 只能将一个字符作为参数,而不能使用完整的字符串。以下是 islowercase 文档的链接: https://docs.julialang.org/en/v1/base/strings/#Base.Unicode.islowercase - GeoffDS

4
您也可以使用正则表达式。正则表达式 ^[a-z\s]+$ 检查您的字符串是否只包含从开头到结尾的小写字母或空格。
julia> f(s)=ismatch(r"^[a-z\s]+$",s)
f (generic function with 1 method)

julia> f("hello world!")
false

julia> f("hello world")
true

julia> f("Hello World")
false

一个不错的正则表达式示例,特别适合那些经常忘记正则表达式语法的人。 - Julia Learner
你的正则表达式中的逗号不也会匹配逗号吗?应该改成r"^[a-z\s]+$"吧? - GeoffDS
1
是的,你说得对!感谢你发现了那个错别字! - niczky12

0

DSM的答案中,特别是islower函数,已经被弃用(可能自2017年以来)。islower已被islowercase替换。因此,DSM的解决方案可以更新为:

julia> f(s) = all(c->islowercase(c) | isspace(c), s);

julia> f("lower and space")
true

julia> f("mixED")
false

如果你喜欢理解式,你也可以使用它们:

julia> g(s) = all([islowercase(letter) | isspace(letter) for letter in s])

julia> g("lower and space")
true

julia> g("mixED")
false

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接