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") &&
  • \$\begingroup\$ Are you trying to parse command line arguments? There might be some libraries that make that even easier. \$\endgroup\$
    – IceArdor
    Jul 12, 2016 at 2:09

1 Answer 1


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?

  • \$\begingroup\$ Wow, I never knew regex could be so useful. Thank you so much for your answer. Learned a lot today \$\endgroup\$
    – lol
    Jul 11, 2016 at 20:45
  • \$\begingroup\$ You can use IsMatch also as a static method. \$\endgroup\$
    – t3chb0t
    Jul 11, 2016 at 21:41
  • \$\begingroup\$ @t3chb0t I was looking for it, but obviously not thoroughly enough - thx for pointing it out, I've updated the code \$\endgroup\$
    – peter
    Jul 12, 2016 at 9:08
  • \$\begingroup\$ If the code is executed frequently, consider to use regex option RegexOptions.Compiled to improve performance. \$\endgroup\$
    – JanDotNet
    Jul 13, 2016 at 6:07
  • \$\begingroup\$ 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. \$\endgroup\$
    – peter
    Jul 13, 2016 at 7:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.