4

I have this ^[a-zA-Z0-9 @&$]*$, but not working for me in few cases.

If someone types

  • A string that only consists of digits (e.g. 1234567)
  • A string starting with a special character (e.g. &123abc)

need to be rejected. Note that a special char can be in the middle and at the end.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Sharpeye500
  • 8,775
  • 25
  • 95
  • 143

2 Answers2

8

You seem to need to avoid matching strings that only consist of digits and make sure the strings start with an alphanumeric. I assume you also need to be able to match empty strings (the original regex matches empty strings).

That is why I suggest

^(?!\d+$)(?:[a-zA-Z0-9][a-zA-Z0-9 @&$]*)?$

See the regex demo

Details

  • ^ - start of string
  • (?!\d+$) - the negative lookahead that fails the match if a string is numeric only
  • (?:[a-zA-Z0-9][a-zA-Z0-9 @&$]*)? - an optional sequence of:
    • [a-zA-Z0-9] - a digit or a letter
    • [a-zA-Z0-9 @&$]* - 0+ digits, letters, spaces, @, & or $ chars
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • If i want to exclude some and include some special character, how i can exclude some, for inclusion, i see it from your regex. – Sharpeye500 Aug 16 '17 at 20:17
  • @Sharpeye500: Sorry, what do you mean? If you do not want to match a char, do not add it to the character class in the first place. – Wiktor Stribiżew Aug 16 '17 at 20:18
  • If have a "." (period) in between characters, currently the regex accepts it. For example, "Test.Work", if i need that to be rejected "." , how do i exclude in the regex. – Sharpeye500 Aug 17 '17 at 15:43
  • @Sharpeye500: [Not sure what you mean](https://regex101.com/r/AcWMcg/1), – Wiktor Stribiżew Aug 17 '17 at 15:51
  • If i type a word say, "Sharpeye500@" it is valid and correct, if i type "Sharpe.Eye500", with a dot in it, it is supposed to be invalid, however with that regex, it says valid, i want to say it as invalid when there is a dot in the word. – Sharpeye500 Aug 17 '17 at 16:36
  • @Sharpeye500: I cannot understand you. A string with `.` [is not matched](https://regex101.com/r/Wcka6Q/1) with the regex above. Please provide a reproducible example. – Wiktor Stribiżew Aug 17 '17 at 16:44
1

you can do it with the following regex

^(?!\d+$)\w+\S+

check the demo here

marvel308
  • 10,288
  • 1
  • 21
  • 32