0

I want to write a script that matches everything that has either a character from the alphabet, a number, and an underscore. Possible valid strings:

asd_asd
Asd_asd
asd_123
123_asd
123_aSD

and so on. What I tried so far is:

if [[ "$LINE" =~ [a-zA-Z0-9_] ]]

But this will match any character that contains also any of these: !@#$%^&*()_+}{|?><`!, and other weird symbols.

I thought about putting the special characters in a list, and ignore a string if it contains one of the characters in the list, but I am afraid I can skip one character.

What is it better to do in this case?

3
  • Can you clarify what strings you want to match? It sounds like you want to match strings that consist entirely of [a-zA-Z0-9_], is that correct? What about the empty (zero-length) string? BTW, your current pattern will match strings that contain at least one [a-zA-Z0-9_] (that is, "@@@@a@@@@" would match, but "@@@@" wouldn't). Commented Mar 20, 2019 at 0:41
  • You probably need a ^ at the beginning and a $ at the end so that the whole like is the pattern And nothing else. You may need to surround the whole thing in single quotes to prevent bash interpolation. Commented Mar 20, 2019 at 0:41
  • I noted that my question was not well formated. I edited it so the examples are clearer. Commented Mar 20, 2019 at 2:08

1 Answer 1

5

[a-zA-Z0-9_] matches only one character. You need to use a pattern like this:

^[a-zA-Z0-9_]+$
  • ^ matches the beginning of the input string,
  • $ matches the end of it,
  • [...]+ matches one or more characters from the character class (a-zA-Z0-9_ in above pattern).
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.