Reputation: 625
I want to create a regular expression that match a string that starts with an optional minus sign -
and ends with a minus sign. In between must begin with a letter (upper or lower case) which can be followed by any combination of letters, numbers and may, at most, contain one asterix (*)
So far I have came up with this
[-]?[a-zA-Z]+[a-zA-Z0-9(*{0,1})]*[-]
Some examples of what I am trying to achieve.
"-yyy-" // valid
"-u8r*y75-" // valid
"-u8r**y75-" // invalid
Upvotes: 0
Views: 1366
Reputation: 22817
^-?[a-z](?!(?:.*\*){2})[a-z\d*]*-$
Alternatively, you can use the following regex to achieve the same results without using a negative lookahead.
^-?[a-z][a-z\d]*(?:\*[a-z\d]*)?-$
** VALID **
-yyy-
-u8r*y75-
** INVALID **
-u8r**y75-
-yyy-
-u8r*y75-
^
Assert position at the start of the line-?
Match zero or one of the hyphen character -
[a-z]
Match a single ASCII alpha character between a
and z
. Note that the i
modifier is turned on, thus this will also match uppercase variations of the same letters(?!(?:.*\*){2})
Negative lookahead ensuring what follows doesn't match
(?:.*\*){2}
Match an asterisk *
twice[a-z\d*]*
Match any ASCII letter between a
and z
, or a digit, or the asterisk symbol *
literally, any number of times-
Match this character literally$
Assert position at the end of the lineUpvotes: 4
Reputation: 65
(-)?(\w)+(\*(?!\*)|\w+)(-)
I used grouping to make it more clear. I changed [a-zA-Z0-9]
to \w
which stands for the same.
(\*(?!\*)|\w+)
This is the important change. Explained in words:
If it is a star \*
and the preceding char was not a star(?!\*)
(called negative lookahead = look at the preceding part) or if it is \w
= [a-zA-Z0-9]
.
Use this site to test: https://regexr.com/
They have a pretty good explaination on the left menu under "Reference".
Upvotes: 0
Reputation: 1568
Try this one:
-(((\w|\d)*)(\*?)((\w|\d)*))-
You can try it here: https://regex101.com/
Upvotes: 0