4

I need help with writing a regular expression for a string that should contain alphanumeric signs and only one of these: #,?,$,%

for example: abx12A#we is ok but fsa?#ds is not ok

I tried with something like /[a-zA-z0-9][#?$%]{0,1}/ but its not working. Any ideas? Thanks

Nasi Jofce
  • 132
  • 2
  • 10

5 Answers5

2

Something like:

^[a-zA-Z0-9]*[#?$%]?[a-zA-Z0-9]*$

should do the trick (and, depending on your regex engine, you may need to escape one or more of those special characters).

It's basically zero or more from the "alpha"-type class, followed by zero or one from the "special"-type class, followed once again by zero or more "alpha".

You can adjust what's contained in each character class as you see fit, but this is the general way to get one of something within a sea of other things.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

If you need to match an empty string, too, you need to use

^[a-zA-Z0-9]*(?:[#?$%][a-zA-Z0-9]*)?$

See the regex demo

Details:

  • ^ - start of string
  • [a-zA-Z0-9]* - zero or more alphanumeric
  • (?:[#?$%][a-zA-Z0-9]*)? - exactly 1 occurrence of:
    • [#?$%] - a char from the set
    • [a-zA-Z0-9]* - zero or more alphanumeric
  • $ - end of string

NOTE: [A-z] is a common typo resulting in serious issues.

If you do not want to allow an empty string, replace * with +:

^[a-zA-Z0-9]+(?:[#?$%][a-zA-Z0-9]+)?$
            ^                    ^
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

try this

const regex = /^[a-zA-z0-9]*[#?$%]?[a-zA-z0-9]*$/

const perfectInputs = [
  'abx12A#we',
  'a#',
  '#a',
  'a#a'
]

const failedInputs = [
  'fsa?#ds'
]

console.log('=========== test should be success ============')
for (const perfectInput of perfectInputs) {
  const result = regex.test(perfectInput)
  console.log(`test ${perfectInput}: ${result}`)
  console.log()
}

console.log('=========== test should be failed ============')
for (const failedInput of failedInputs) {
  const result = regex.test(failedInput)
  console.log(`test ${failedInput}: ${result}`)
  console.log()
}
Alongkorn
  • 3,968
  • 1
  • 24
  • 41
1

If the special character can be at the begining or at the end of the string, you could use lookahead:

^(?=[^#?$%]*[#?$%]?[^#?$%]*$)[a-zA-Z0-9#?$%]+$
Toto
  • 89,455
  • 62
  • 89
  • 125
1
/^(?=[^#?$%]*[#?$%]?[^#?$%]*$)[a-zA-Z0-9#?$%]*$/
  \__________^^^^^^^_________/ -------------------- not more than once
                              \_____________/ ----- other conditions
Qwertiy
  • 19,681
  • 15
  • 61
  • 128