# Checking if a line in a file contains user.Handle and '-r'+any single digit number

The title pretty much explains everything. I'm try to check if a line in a file contains user.Handle and '-r'+any single digit number, AND that the aforementioned user.Handle does not contain '-r'. I'm sure there is an easier way to do this. And I'm sorry if this made your eyes bleed.

if (line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r1") || line.Contains(user.Handle) &&
!user.Handle.Contains("-r") && line.Contains("-r2") ||
line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r3") || line.Contains(user.Handle) &&
!user.Handle.Contains("-r") && line.Contains("-r4") ||
line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r5") || line.Contains(user.Handle) &&
!user.Handle.Contains("-r") && line.Contains("-r6") ||
line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r7") || line.Contains(user.Handle) &&
!user.Handle.Contains("-r") && line.Contains("-r8") ||
line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
line.Contains("-r9"))

• Are you trying to parse command line arguments? There might be some libraries that make that even easier. Jul 12, 2016 at 2:09

If I see it correctly, you could already simplify your code by saying

if (line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
(line.Contains("-r1") || line.Contains("-r2") || ... line.Contains("-r9"))


That should be basically the same thing as the above. Now when you look at the last part, you could simplify it to a regular expression -r\d (not sure if - needs to be escaped here) So the final version could look like this:

if (line.Contains(user.Handle) && !user.Handle.Contains("-r") &&
Regex.IsMatch(line, "-r\\d"))


did I get your question? Did I miss anything?

• Wow, I never knew regex could be so useful. Thank you so much for your answer. Learned a lot today
– lol
Jul 11, 2016 at 20:45
• You can use IsMatch also as a static method. Jul 11, 2016 at 21:41
• @t3chb0t I was looking for it, but obviously not thoroughly enough - thx for pointing it out, I've updated the code Jul 12, 2016 at 9:08
• If the code is executed frequently, consider to use regex option RegexOptions.Compiled to improve performance. Jul 13, 2016 at 6:07
• This is a very old post from 2005: blog.codinghorror.com/to-compile-or-not-to-compile - but I've seen often people saying that you shouldn't use the compile option unless you know what you're doing. Jul 13, 2016 at 7:45