Regex to find strings with only letters or numbers or both

I am searching for strings with only letters or numbers or both. How could I write a regex for that?


You can use following regex to check if the string contains letters and/or numbers



  1. ^: Starts with
  2. []: Character class
  3. a-zA-Z: Matches any alphabet
  4. 0-9: Matches any number
  5. +: Matches previous characters one or more time
  6. $: Ends with

RegEx101 Demo

"abc&@*(2743438" !~ /[^a-z0-9]/i # => false
"abc2743438"     !~ /[^a-z0-9]/i # => true

This example let to avoid multiline anchors use (^ or $) (which may present a security risk) so it's better to use \A and \z, or to add the :multiline => true option in Rails. Only letters and numbers:


Or if you want to leave - and _ chars also:


Need Your Help

Looping threads accessing pthread mutex

c linux multithreading scheduling mutex

im building this application in which i have a client represented by a thread, running in loop (until it receives the instruction to terminate) trying to access a critical section of data in the se...

trying format json a certain way in PHP using array from mysql

php mysql json

I am trying to build a restful web service for my website. I have a php mysql query using the following code: