Fix regex

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

for example: abx12A # we are fine, but fsa? #ds does not work

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

+4
source share
5 answers

Sort of:

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

should do the trick (and, depending on your regular expression engine, you might need to avoid one or more of these special characters).

alpha-type, "special", "".

, , , - .

+3

,

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

regex

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

: [A-z] , .

, * +:

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

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()
}
Hide result
+1
source

If the special character can be at the beginning or end of a line, you can use lookahead:

^(?=[^#?$%]*[#?$%]?[^#?$%]*$)[a-zA-Z0-9#?$%]+$
+1
source
/^(?=[^#?$%]*[#?$%]?[^#?$%]*$)[a-zA-Z0-9#?$%]*$/
  \__________^^^^^^^_________/ -------------------- not more than once
                              \_____________/ ----- other conditions
+1
source

Source: https://habr.com/ru/post/1659513/


All Articles