0

I want to check the given string is alphanumeric or not. i.e. the expected output is as follows

  • 123 should retun false
  • abc should retun false
  • a123 should retun true
  • 1a23 should retun true

I tried with the ^[a-zA-Z0-9]*$ regex. It is not working as expected. Can anyone suggest the working peggyjs regex? Thanks.

Benk I
  • 185
  • 13
  • 1
    Try this: [`(?=.*[a-zA-Z])(?=.*\d)^[a-zA-Z0-9]+$`](https://regex101.com/r/bwpppz/1) – Alireza Sep 21 '21 at 12:07
  • Getting this error `peg$SyntaxError: Expected "!", "$", "&", "(", ".", "@", character class, comment, end of line, identifier, literal, or whitespace but "?" found.` Can you give the solution for this? Thanks – Benk I Sep 21 '21 at 12:22
  • How about this? [`^[0-9]+[a-zaA-Z]+[a-zA-Z0-9]*$|^[a-zaA-Z]+[0-9]+[a-zA-Z0-9]*$`](https://regex101.com/r/bwpppz/2) – Alireza Sep 21 '21 at 12:31
  • Different error `peg$SyntaxError: Expected "!", "$", "&", "(", ".", character class, comment, end of line, identifier, literal, or whitespace but "^" found.` – Benk I Sep 21 '21 at 12:32
  • 1
    @BenkI Did you look at the examples how to implement this? https://github.com/peggyjs/peggy/tree/main/examples or perhaps the readme? – The fourth bird Sep 21 '21 at 12:33
  • @Thefourthbird I have looked at it, but I didn't get it. So I have posted the question here. – Benk I Sep 21 '21 at 12:36

2 Answers2

0

You can assert not only digits, and match at least a single digit restricticting to match to only a-z or a digit.

Using a case insensitive match:

^(?!\d+$)[a-z]*\d[a-z\d]*$

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Getting this error `peg$SyntaxError: Expected "!", "$", "&", "(", ".", character class, comment, end of line, identifier, literal, or whitespace but "^" found.` Can you give the solution for this? Thanks. – Benk I Sep 21 '21 at 12:19
  • @BenkI I am currenly on a mobile device and not able to test the peggy software. Perhaps if you update your question with what you have tried, it will be clearer to what kind of a solution you are looking for. Currently it is closed as for the regex solution there is a duplicate answer found. – The fourth bird Sep 21 '21 at 13:14
-1

If you know the order (letters then numbers for example) you can do .*[a-zA-Z].*[0-9]

But I assume you can't make such assumptions so I would use the slightly more complex ^(?=.*[a-zA-Z])(?=.*[0-9]).* which means "a letter somewhere later, and also a number somewhere later".

PS : you can replace all [0-9] by \d if you like.

Edit : that's only assuming you don't get other kinds of characters, use Alireza's regex instead if you need to.

LogicalKip
  • 514
  • 4
  • 13
  • Getting this error `peg$SyntaxError: Expected "!", "$", "&", "(", ".", character class, comment, end of line, identifier, literal, or whitespace but "^" found.` Can you give the solution for this? Thanks – Benk I Sep 21 '21 at 12:22