Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to identify MQTT topics

Tags:

c#

regex

I'm trying to get a regex in C# to parse an mqtt topic to know which action to perform for each topic type we defined in our system. We have two topics that must be differentiated:

  1. cd/hl/projects/{project_id}/var/{var_name}
  2. cd/hl/projects/{project_id}/var/{var_name}/write

{project_id} can be any character but a line break (\n). Can be empty {var_name} can be any character but a line break (\n). Can be empty

to match string 2 I use the following and it's working in all cases i tested:

    ^cd/hl/projects/.*/var/.*/write$

So far so good. But I fail when I try to match 1. without also giving a match on 2. using the following regexs:

    ^(cd/hl/projects/.*/var/.*)(?!/write)$

    what I think should do (but it doesn't):
    (cd/hl/projects/.*/var/.*)  #match any projects and var_names
    (?!/write)                  #not match if /write appears

The problem is that I can't stop matching strings that have /write in the end like:

    cd/hl/projects/4d69439d-8c13-4e83-9ed5-60659d953f9f/var/test_count_one/write

I just want not to match the string above but only with:

    cd/hl/projects/{project_id}/var/{var_name}

My questions are: I'm following the right approach? What am I missing? How can I achieve my goal?

Thanks

like image 963
Yevheniy Tymchishin Avatar asked Jan 25 '26 23:01

Yevheniy Tymchishin


1 Answers

The subparts should contain no /, not just \n. You should replace .* with [^/\n]* and use

REGEX 1: ^cd/hl/projects/([^/\n]*)/var/([^/\n]*)
REGEX 2: ^cd/hl/projects/([^/\n]*)/var/([^/\n]*)/write$

See the regex demo 1 and regex demo 2.

The [^/\n]* negated character class matches any 0+ (due to *) chars other than / and \n.

like image 190
Wiktor Stribiżew Avatar answered Jan 27 '26 16:01

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!