-1

I'm looking for a solution in regex. I have a full name for which the allowed characters are a-z, A-Z, space and /,-.@'

Also it should not start with a blank character/space.

So basically the following names are accepted.

  1. Anjith Sasindran
  2. Anjith@ Sasindran'
  3. Anjith
  4. Anjith/,Sasi@n'ran
  5. An-. Sasindr@

And the following are not

  1. An%jith Sasindran
  2. Anjit*) Sasindran

Basically anything other than the ones I listed above.

I'm not sure how to do the same. I've very little knowledge in regex b/w. So any help would be appreciated.

capt.swag
  • 10,335
  • 2
  • 41
  • 41

2 Answers2

1

use:

^[^\s][ A-Za-z-'@.,/]*$
  • ^[^\s] checks that there is no whitespace at the beginning
  • A-Za-z accepts all the alphabets in the given string
  • -'@.,/ accepts only these special characters
  • * matches 0 or more preceding token
p_flame
  • 102
  • 6
  • What does the $ sign do at the end? Why can't the * be a +? The solution you offered works perfectly for my situation, but would like to know a bit more as you've given a good explanation. – capt.swag Nov 05 '20 at 17:16
  • Test it with `%` as input. It will tell you that it's a match. The [^\s]` means **any** character **except** a blank one. – amanin Nov 05 '20 at 17:51
  • @capt.swag ```$``` at the end means that it would accept those strings that ends with this regex condition. Better to understand would be as @amanin said, test it with your example ```An%jith Sasindran``` and it would still match the ```An``` part of it. Also ```+``` sign would match 1 or more preceding token whereas ```*``` matches 0 or more. In these examples that you provided ```*/+``` both would work, but you need to use it according to your situation – p_flame Nov 05 '20 at 19:26
0

With regular expressions, you can define classes of characters like the follwing: [\sa-zA-Z@\.,\-'/].

With that, you define one "allowed" character. You can specify a sequence of it by adding plus operator : [\sa-zA-Z@\.,\-'/]+.

Now, to avoid texts starting with blank character, you can create a character class with all wanted characters except spaces [a-zA-Z@\.,\-'/].

So, now, the final regex is "any of the wanted characters except a blankspace, followed by any of wanted characters a certain number of times" : [a-zA-Z@\.,\-'/][\sa-zA-Z@\.,\-'/]* With java, you must use Pattern class to apply regex checks on a string:

var nameMatcher = Pattern.compile("[a-zA-Z@\\.,\\-'/][\\sa-zA-Z@\\.,\\-'/]*").asPredicate();
if (nameMatcher.test("Anjhit@")) System.out.println("Name match !");

You can get a lot of information with Oracle documentation.

amanin
  • 3,436
  • 13
  • 17