Francis Smart
Francis Smart

Reputation: 4065

Julia: Check if first Letter in String Is Lowercase preferred syntax

Let's say I have a string x="1. this should be capitalized"

Right now if I want to check if the first letter is capitalized

s = "1. (t)his should be capitalized"
s2 = match(r"^.*?([a-zA-Z])", s).captures[1]
@show all(islowercase, s2)
# true

If I do islowercase(s2) I get a MethodError. Though I could also do @show uppercasefirst(s2) != s2 but this seems unnecessarily verbose.

Upvotes: 1

Views: 573

Answers (3)

A.Yazdiha
A.Yazdiha

Reputation: 1378

You can alternatively do the following:

 s = "1. (t)his should be capitalized";
 s2 = s[findfirst(r"[:alpha]", s)[1]]
 islowercase(s2)

Upvotes: 1

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22245

No need for regex. Just use islowercase on your string directly (via splatting and broadcasting), and get the index of the first true result.

findfirst(  islowercase.([ x... ])  )

If your strings do not have consistent syntax, you could also check if it is a letter.

findfirst( islowercase.( [ x... ] ) .& isletter.( [ x... ] ) )

Upvotes: 0

fredrikekre
fredrikekre

Reputation: 10984

As you have noted, islowercase works with individual characters, and not strings. To extract the first character from the regex match string you can use first:

julia> s = "1. (t)his should be capitalized";

julia> s2 = match(r"^.*?([a-zA-Z])", s).captures[1]
"t"

julia> islowercase(first(s2))
true

Upvotes: 3

Related Questions