-1

How can I create a regex expression that will match only letters or letters with numbers? I've tried something like (?:[A-Za-z0-9]+|[A-Za-z]+). The regex should give the following result:

123a --> true 123 --> false abc --> true abc4 --> true

  • 1
    In other words, you wish to match a string that contains only letters and digits and contains at least one letter. When expressed that way you can translate the requirement to a regex directly. How do you require a letter? How do you require the string to only contain certain characters? – Cary Swoveland Mar 16 '20 at 20:19

2 Answers2

1

Use:

^(?i)(?=.*[a-z])[a-z\d]+$

Demo & explanation

Toto
  • 89,455
  • 62
  • 89
  • 125
0

You can try awk. If your text file contains the lines:

123a
123
abc
abc4

Use this one liner:

awk '{ if ($0 ~ /[0-9]/ and $0 ~ /[A-Za-z]/) {print $0 " --> true"} else { print $0 " --> false"  }  }' test.txt

or pretty it up as:

awk '{ 
    if ($0 ~ /[0-9]/ and $0 ~ /[A-Za-z]/) {
        print $0 " --> true"
    } else {
        print $0 " --> false"
    }
}' test.txt

Result

123a --> true
123 --> false
abc --> true
abc4 --> true

Explanation

  • check if the line contains a number. If not, print the line with true
  • if the line does contain a number, also check if it contains a letter. If so, print the line with true
  • otherwise, print false
zedfoxus
  • 35,121
  • 5
  • 64
  • 63