cod3min3
cod3min3

Reputation: 625

How to make regex that can take at most one asterisk in character class?

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

Answers (3)

ctwheels
ctwheels

Reputation: 22817

Code

See regex in use here

^-?[a-z](?!(?:.*\*){2})[a-z\d*]*-$

Alternatively, you can use the following regex to achieve the same results without using a negative lookahead.

See regex in use here

^-?[a-z][a-z\d]*(?:\*[a-z\d]*)?-$

Results

Input

** VALID **
-yyy-
-u8r*y75-

** INVALID **
-u8r**y75-

Output

-yyy-
-u8r*y75-

Explanation

  • ^ 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 line

Upvotes: 4

Dark Smile
Dark Smile

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

SyncroIT
SyncroIT

Reputation: 1568

Try this one:

-(((\w|\d)*)(\*?)((\w|\d)*))-

You can try it here: https://regex101.com/

Upvotes: 0

Related Questions