What is the correct way to make a regex that accepts all letters and a selection of characters? [duplicate]

  • A+
Category:Languages

I need a Regex that accepts all letters(lowercase & uppercase), numbers and these characters/symbols ('-','_','@','.'). It is not required to be in the form of an Email address. The characters can be positioned anywhere in the word. It also should not accept spaces and the word length must be 8 or more.

This is what I have so far.

^(?=/S{8})[a-zA-Z]/w*(?:/./w+)*(?:@/w+/./w{2,4})?$ 

 


You may use the following regex:

^[a-zA-Z0-9_@.-]{8,}$ 

Details

  • ^ - start of string
  • [a-zA-Z0-9_@.-]{8,} - 8 or more ASCII letters, digits, ., _, @ or -
  • $ - end of string.

See the regex demo.

Watch out for /w in Android, it matches all Unicode letters and digits by default (but not in Java).

In Android/Java, when using it with .matches(), you may remove the ^ and $ anchors as this method requires a full string match:

String regex = "[a-zA-Z0-9_@.-]{8,}"; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: