Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex Expression Issue

Tags:

c#

regex

I am trying to parse the following line:

"\#" TEST #comment hello world

In my input, the #comment always comes at the end of the line. There may or may not be a comment, but if there is, its always in the end of the line.

I used the following Regex to parse it:

(\#.+)?

I have the RegexOption.RightToLeft on. I expected it to pull #comment hello world. But instead it is pulling "#" TEST #comment hello world"

Why is my Regex expression not pulling the right thing and what is the valid Regex expression I need to make it pull correctly?

like image 986
Icemanind Avatar asked Jul 20 '26 20:07

Icemanind


1 Answers

The important question is: How do you see the difference between the # at the end of the line and the # that starts the comment? Let's assume for simplicity that the last # starts a comment.

In that case, what you want to match is

  • one #
  • an arbitrary sequence of text not containing #
  • until the end of the line

So let's put that into a regex: #[^#]*$. You don't need RightToLeft for it. As far as I know, you also don't need to escape # in C# regular expressions.

Of course, if you provide information on how to see the difference between a "valid" # and a "comment-starting" #, a more elegant solution could be found that allows for # within comments.

like image 144
Heinzi Avatar answered Jul 22 '26 11:07

Heinzi