Search code examples
regexbrackets

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:

  • brackets just one time, doesn't matter where
  • Text or numbers before and after brackets optional
  • numbers within the brackets

Example what is allowed:

  • [32] text1
  • text1 [5]
  • text1 [103] text2
  • text1
  • [123]
  • [some value [33]] (maybe to complicated, would be not so important?)

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

  • [32] 11
  • 11 [5]
  • 11 [103] 22
  • 11
  • [123]

no match:

  • [12] xxx [5] (brackets are more than one time)
  • [aa] xxx (no number within brackets)

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!


Solution

  • 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.