bokaj92
bokaj92

Reputation: 39

Regex that doesn't recognise a pattern

I want to make a regex that recognize some patterns and some not.

_*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?<!_)

The sample of patterns that i want to recognize:

a100__version_2
_a100__version2

And the sample of patterns that i dont want to recognize:

100__version_2
a100__version2_
_100__version_2
a100--version-2

The regex works for all of them except this one:

a100--version-2

So I don't want to match the dashes.

I tried _*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?<!_) so the problem is at [^-]

Upvotes: 1

Views: 26

Answers (1)

The fourth bird
The fourth bird

Reputation: 163577

You could write the pattern like this, but [^-]* can also match newlines and spaces.

To not match newlines and spaces, and matching at least 2 characters:

^_*[a-zA-Z][a-zA-Z0-9_][^-\s]*$(?<!_)

Regex demo

Or matching only word characters, matching at least a single character repeating \w* zero or more times:

^_*[a-zA-Z]\w*$(?<!_)
  • ^ Start of string
  • _* Match optional underscores
  • [a-zA-Z] Match a single char a-zA-Z
  • \w* Match optional word chars (Or [a-zA-Z0-9_]*)
  • $ End of string
  • (?<!_) Assert not _ to the left at the end of the string

Regex demo

Upvotes: 1

Related Questions