-2

I have alphanumeric string where the only #.- are the allowed special characters

my current regex is ^[a-zA-Z0-9][-#._ a-zA-Z0-9 ]+$

which is accepting string as Exam1,Exam#1,Exam1.1 but is also accepting Exam ##1,Exam 1..1

How can I make it match special character only once

azro
  • 53,056
  • 7
  • 34
  • 70
00Shunya
  • 85
  • 10
  • Why don't you just count the number of occurrences? – ctwheels Apr 12 '18 at 14:25
  • Possible duplicate of [Java: How do I count the number of occurrences of a char in a String?](https://stackoverflow.com/questions/275944/java-how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string) – ctwheels Apr 12 '18 at 14:25
  • If you do not want repeating special character allowed, what about this case? For example, `Exam #.1 Exam 1.#1 Exam 1.-1` Is this case all right? – Thm Lee Apr 12 '18 at 15:17

2 Answers2

0

First let me explain you regex

^[a-zA-Z0-9][-#._ a-zA-Z0-9 ]+$

Start with character a-z or A-Z or 0-9 followed by atleast one or more of the followed characters.

So move the special character [-#.] into seperate character class and surrounded it with other characters [-#._ a-zA-Z0-9 ]

^[a-zA-Z0-9][_a-zA-Z0-9 ]+[-#.]?[_a-zA-Z0-9 ]+$
AbhishekGowda28
  • 994
  • 8
  • 19
0

I assume you talk mean that their can be only one group of special caracters, the following statement should do the trick:

^[a-zA-Z0-9][a-zA-Z0-9 ]*[-#.]*[a-zA-Z0-9 ]*

I'll break it down:

^[a-zA-Z0-9] means it must start with one alphanumeric character

[a-zA-Z0-9 ]* means there might be following alphanumeric characters

[-#.]* means somewhere in the string, there can be a sequence of special characters

[a-zA-Z0-9 ]* means string might end with a sequence of alphanumeric characters or special characters

The first and second part are close but different to prevent a space to be placed at the beginning.

The fact of wrapping the special characters sequence the same structure with * allows it to be anywhere.

Some references

IPessers
  • 66
  • 1
  • 8