2

I've trying to get a regular expression to work with no luck. I've been able to to limit the expression to an alphanumeric number with 10 digits:

(^[a-zA-Z0-9]{10}+$)

however i am also trying to get it allow the $ character with only 1 match in any position.

it should come up as true for something like, pQp3b8ar$8 or k7DdRoB$5W.

2 Answers2

4

Three general notes:

^[a-zA-Z0-9$]{10}$
  • the parentheses are not necessary
  • {10}+ does not make much sense, drop the plus (there's no need for a possessive quantifier on a fixed count)
  • if you want to allow a dollar sign, just add it to the character class

To allow a dollar sign only once, you can use an extended version of the above:

^(?=[^$]*\$[^$]*$)[a-zA-Z0-9$]{10}$

The (?=[^$]*\$[^$]*$) is a look-ahead that reads

(?=        # start look-ahead
  [^$]*    #   any number of non-dollar signs
  \$       #   a dollar sign
  [^$]*    #   any number of non-dollar signs
  $        #   the end of the string
)          # end of look-ahead

It allows any characters on the string but the dollar only once.


Another variant would be to use two look-aheads, like this:

^(?=[^$]*\$[^$]*$)(?=[a-zA-Z0-9$]{10}$).*

Here you can use the .* to match the remainder of the string since the two conditions are checked by the look-aheads. This approach is useful for password complexity checks, for example.

Community
  • 1
  • 1
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Thats close, but how would you only accept 1 $ allowed? If I put in qFYg64E$h$ i want it to come up false as compared to true for qFYg64Ehh$. – John Kramer Nov 18 '12 at 06:13
  • 1
    Nice, also thanks for the explanation as well, makes it easier to know whats going on. – John Kramer Nov 18 '12 at 06:26
0

You could try to match a string that contains two strings of any number of alphanumeric characters with a $ in the middle.

(^[a-zA-Z0-9]+\$[a-zA-Z0-9]+$)

You can always check the length of ten after the regex.

Spoike
  • 119,724
  • 44
  • 140
  • 158