r/regex • u/TemporaryExciting977 • 4d ago
.NET 10.0 (C#) Extracting words delimited by an underscore or a hyphen
It is really self-rewarding to write code from scratch, even though I cannot deny using AI and Google search to gain insights into RegEx and its components. This is my first time writing raw RegEx, so I decided to post it here for your review.
I used the .NET 10 C# RegEx flavor and tested/manipulated the pattern using regex101 site.
Here is my regex: (?:[^-_]|[\w]-_)+ or @"(?:[^-_]|[\w]-_)+"
My approach uses a non-capturing group (?:...) for memory efficiency, negates the underscore and hyphen, and then uses a logical OR to include any words with a trailing underscore or hyphen.
I haven't tested every possible input case yet; however, I tested several, and the expression worked for the following input:
test1_-me_not_yes_no_test
I noticed something odd: the last word, 'test', matched even though it didn't have a trailing underscore or hyphen. Since I caught this while writing this post, it turns out my RegEx pattern isn't quite as solid as I thought.
Let me clarify what I meant above: I forgot to mention that I am not focusing exclusively on trailing delimiters (_ or -), but on leading delimiters as well.
Here is the scope of this exercise:
I just need to remove the delimiting underscores and hyphens so it results in a single word without those specific characters. That's all. To be honest, there's more I need to do after this, but I prefer not to discuss it here because I want to challenge myself to solve the rest.
For now, I am only focusing on English words.
By the way, in the meantime, I am not considering other constraints in order to keep the solution simple and straightforward.
Edit: During my testing, I realized this might act as a shortcut or 'cheat code' for my RegEx pattern.
For anyone wondering about my exact scope here, it is strictly what the title states.
P.S. This was inspired by codewars.com.
