split text and inline comment with regex

Viewed 91

My goal is to parse these two types of text: Any#text;more ; a comment or Any#text;more # a comment and Any#text;no comment

It is an arbitrary line of text with an optional comment. The comment indicator is a # or ; preceded by at least one whitespace.

My approach before was ^(?<value>([^#;])+)(\s*[#;](?<comment>.*))?$ that is a group value that accepts everything except the comment indicators followed optionally by the indicator and a group comment.

This worked out well until I realized, that I sometimes have the comment indicator chars in the value, too.

I'm trying grouping, pos/neg lookahead/behind in various combinations with the regex101.com verifier and debugger since a hour now and am totally stuck.

The best I could get is ^(?<value>(.+(?=\s#|\s;)))(\s*[#;](?<comment>.*))?$ which splits very good value and comment, but now the comment is somehow mandatory. Can anyone point me in the right direction, please?

ps: using this inside c# and yes, it has to be regex, and no, its no homework ;-)

1 Answers

You may try this refactored regex for the cases you have described:

^(?<value>.+?(?=\s[;#]|$))(?:\s*[#;](?<comment>.*))?$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?<value>: Start named capture group value
    • .+?: Match 1+ of any characters (non-greedy)
    • (?=\s[;#]|$): Lookahead to assert that we have a whitespace followed by # or ; OR else (for lines with no comments) end of line ahead
  • ): End capture group value
  • (?:: Start a non-capture group
    • \s*[#;]: Match 0+ whitespaces followed by # or ;
    • (?<comment>.*): named capture group comment to match everything till end
  • )?: End optional non-capture group
  • $: End
Related