0

I am trying to write Regex for a 3 letter alphabetical string which is not empty. I have tried the following

(?=(^$)|(\s+$))(?=[A-Z]{3})

I know that ?= acts as and operator,(^$)|(\s+$) check for non empty and white space, but the following regex is not working. unable to find out whats wrong in this. Any help would be appreciated.

My regex should check first whether the string is empty and if the string is not empty then it should check whether is alphabetical and length is 3 following are examples

1."" - should fail

2."LGW" - Should pass

3."LGWE" - should fail

4."LG!@"- should fail

5."12L"-should fail

phani sekhar
  • 107
  • 1
  • 1
  • 13

1 Answers1

7

In your case then ^[A-Z]{3}$ should do what you are after.

It will ensure that the entire string is made up from 3 upper case letters. If you want to also match lower case letters, just use this: ^[A-Za-z]{3}$.

An example of the expression is available here.

EDIT: As per your comment, which seems to go against one of your test cases in your question, if you want to also accept empty strings then you will need to change ^[a-z]{3}$ to ^([a-z]{3})?$. This will mean that the 3 letters are optional.

npinti
  • 51,780
  • 5
  • 72
  • 96
  • what should i change in this regex to satisfy the following. It can be empty and if it is not empty then it should contain only alphabets of length 3. Tried this but no luck (^[\s]*$)|([a-z]{3}) . i know this is a new question. It would be very helpful if a solution for this also suggested. – phani sekhar Aug 24 '15 at 10:21
  • @phanisekhar: If it is empty then you should use the `.length` property on the string you are proving as input, no need for regular expressions. – npinti Aug 24 '15 at 10:23
  • @phanisekhar in one of the examples you say "" should fail. is that wrong? the string can be empty? – Siddharth Aug 24 '15 at 10:31
  • @npinti I cant use .length, i have to validate it only through regex. – phani sekhar Aug 24 '15 at 10:34
  • @Siddharth This is different scenario. Value can be either empty or not empty and if it is not empty then it should be only lower case alphabets with length 3. – phani sekhar Aug 24 '15 at 10:35
  • @phanisekhar: I've updated my answer. Please also note that your lower case requirement goes against the examples posted... – npinti Aug 24 '15 at 10:38