lukas-adrian
lukas-adrian

Reputation: 35

Regex with one open and close bracket within an number

since few days I am sitting and fighting with the regular expression without any success

My first expression, what I want:

Example what is allowed:

My second expression is similar but just numbers before and after the brackets instead text

no match:

That's what I did but is not working because I don't know how to do with the on-time-brackets:

^.*\{?[0-9]*\}.*$

From some other answer I found also that, that's looks good but I need that for the numbers:

^[^\{\}]*\{[^\{\}]*\}[^\{\}]*$

I want to use later the number in the brackets and replace with some other values, just for some additional information, if important.

Hope someone can help me. Thanks in advance!

Upvotes: 1

Views: 1409

Answers (1)

NullVoid
NullVoid

Reputation: 847

This is what you want:

^([^\]\n]*\[\d+\])?[^[\n]*$

Live example

Update: For just numbers:

^[\d ]*(\[\d+\])?[\d ]*$

Explaination:

  • ^ Start of line
  • [^...] Negative character set --> [^\]] Any character except ]
    • * Zero or more length of the Class/Character set
  • \d 0-9
    • + One or more length of the Class/Character set
  • (...)? 0 or 1 of the group
  • $ End of line

Note: These RegExs can return empty matches.

Thanks to @MMMahdy-PAPION! He improved the answer.

Upvotes: 2

Related Questions