'How to check if a string is alphanumeric?

I can use occursin function, but its haystack argument cannot be a regular expression, which means I have to pass the entire alphanumeric string to it. Is there a neat way of doing this in Julia?



Solution 1:[1]

but its haystack argument cannot be a regular expression, which means I have to pass the entire alphanumeric string to it.

If you mean its needle argument, it can be a Regex, for eg.:


julia> occursin(r"^[[:alnum:]]*$", "adf24asg24y")
true

julia> occursin(r"^[[:alnum:]]*$", "adf24asg2_4y")
false

This checks that the given haystack string is alphanumeric using Unicode-aware character class [[:alnum:]] which you can think of as equivalent to [a-zA-Z\d], extended to non-English characters too. (As always with Unicode, a "perfect" solution involves more work and complication, but this takes you most of the way.)

If you do mean you want the haystack argument to be a Regex, it's not clear why you'd want that here, and also why "I have to pass the entire alphanumeric string to it" is a bad thing.

Solution 2:[2]

I'm not sure your assumption about occursin is correct:

julia> occursin(r"[a-zA-z]", "ABC123")
true

julia> occursin(r"[a-zA-z]", "123")
false

Solution 3:[3]

As has been noted, you can indeed use regexes with occursin, and it works well. But you can also roll your own version, quite simply:

isalphanumeric(c::AbstractChar) = isletter(c) || ('0' <= c <= '9')
isalphanumeric(str::AbstractString) = all(isalphanumeric, str)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nils Gudat
Solution 3 DNF