Search code examples
stringjuliaalphanumeric

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

  • 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.