Are regular expressions worth the hassle?

后端 未结 24 1258
说谎
说谎 2020-12-03 13:58

It strikes me that regular expressions are not understood well by the majority of developers. It also strikes me that for a lot of problems where regular expressions are use

相关标签:
24条回答
  • 2020-12-03 14:00

    The most hassle I see is when people try to parse non-regular languages with regular expressions (yes, that includes all programming and many markup languages, yes, also HTML). I sometimes wish all coders had to demonstrate that they have understood at least the difference between context-free and regular languages before they are allowed to use regular expressions. Alternatively, they could get their regex license revoked when they are caught trying to parse non-regular languages with them. Yes, I'm joking, but only half.

    The next problem arises when people try to do more than character matching in a regular expression, for example, checking for a valid date, perhaps even including leap year considerations (this could also lead to regex license revokation).

    Regular expressions really are just a convenient shorthand for a finite state automaton (You know what that is, don't you? Where is your regex license, please?). The problems come from people expecting some kind of magic from them, not from the regular expressions themselves.

    0 讨论(0)
  • 2020-12-03 14:00

    Regex is one tool among many. But as many craftsmen will attest, the more tools you have at your disposal, and the more skilled you are at using them, the more likely you will become a Master Craftsman.

    Is Regex worth the hassle to you? Dunno. Depends how seriously you take what you do.

    0 讨论(0)
  • 2020-12-03 14:02

    With great power comes great responsibility!

    Regular expressions are great, but there can be a tendancy to over-use them! There are not suitable in all cases!

    0 讨论(0)
  • 2020-12-03 14:03

    In .NET regex'es you can have comments, and break them up into multiple lines, use indenting etc. (I don't know about other dialects...)

    Use the "ignore pattern whitespace" setting, and either # for commenting out the rest of the line, or "(#comments)" in your pattern...

    So if you wanted to, you can actually make them sort of readable/maintainable...

    0 讨论(0)
  • 2020-12-03 14:04

    It's a lot easier to see at first glance that a regex is probably correct. Why would I write a long state machine in code (probably containing bugs at first) when I could write a simple one line regex?

    Regexes may be considered "write only", but I think that is sometimes a benefit. When writing a relatively simple regex from scratch, it's pretty easy to get it right.

    0 讨论(0)
  • 2020-12-03 14:05

    Think of regular expressions as the lingua Franca of string processing. You simply need to know them if you are going tocode in a professional capacity. Unless you just write SQL maybe.

    0 讨论(0)
提交回复
热议问题