ProfNimrod ProfNimrod - 4 months ago 14
C# Question

What is the regex for testing whether '[x,y]' is contained at the end of any string?

I have some strings that contain multiple words (separated by spaces, but can also contain ANY characters). Some of them end with grid coordinates surrounded by square brackets, e.g., [x,y], where x,y are any integer less then 13 (although the test for < 13 isn't absolutely necessary).

I want to be able to identify the strings that end with a grid coordinate, and then remove that part of the string and trim the remaining of whitespace from the right hand side.

I think the use of a regex should do this, but I am unfamiliar with the syntax... although trying to learn it.

An example string is:

Hex Beam [0,0]

(note that there is nothing stopping the use square brackets in the section before the grid coordinate - so the test has to be for how the string ends)

... and I need

Hex Beam

Lastly, I am coding in C#.


I've tried


but this doesn't guarantee that the required pattern is necessarily at the end.



did the trick.


As pointed out by u/Jefré N. in the comments, this should get the job done:

        string NewTestString = "Hex [1,1] Beam [12,9]";
        Regex rx = new Regex(@"\[[0-9]*[,][0-9]*\]$");
        string OutPut = rx.Replace(NewTestString, "").TrimEnd();