Q:

Dollar sign forced left or right

I'm learning regular expressions and testing my expressions on regexpal.com. So far this regular expression matches any number less than 1000:

^\d{1,3}$

For example: 999 gets matched.
I'm being asked to match the expression only if a $ sign is placed left or right. I have no idea how to do this. So I thought:
A dollar sign on the right can be detected by doing this. For example 999$ gets matched:

^\d{1,3}\$$

A dollar sign on the left can be detected by doing this. For example $999 gets matched:

^\$\d{1,3}$

I thought, using the operator ?, I can accept the $ sign on left and on right:

^(\$)?\d{1,3}(\$)?$

This solves partially the problem, the regular expression now matches:

999$
$999

But also matches:

$999$
999

How can I fix my regular expression forcing at least a dollar sign right or left (but not both) and rejecting a number with no $ (we can't use character count 9 and 99 and 999 are all matched)?

A:

One of the ways you can do is using pipe | (alternative operator):
^(\$\d{1,3}|\d{1,3}\$)$

See DEMO

