Why can't Regular Expressions use keywords instead of characters?

后端 未结 14 3149
甜味超标
甜味超标 2021-02-20 06:46

Okay, I barely understand RegEx basics, but why couldn\'t they design it to use keywords (like SQL) instead of some cryptic wildcard characters and symbols?

Is it for pe

相关标签:
14条回答
  • 2021-02-20 07:15

    You really want this?

    Pattern findGamesPattern = Pattern.With.Literal(@"<div")
        .WhiteSpace.Repeat.ZeroOrMore
        .Literal(@"class=""game""").WhiteSpace.Repeat.ZeroOrMore.Literal(@"id=""")
        .NamedGroup("gameId", Pattern.With.Digit.Repeat.OneOrMore)
        .Literal(@"-game""")
        .NamedGroup("content", Pattern.With.Anything.Repeat.Lazy.ZeroOrMore)
        .Literal(@"<!--gameStatus")
        .WhiteSpace.Repeat.ZeroOrMore.Literal("=").WhiteSpace.Repeat.ZeroOrMore
        .NamedGroup("gameState", Pattern.With.Digit.Repeat.OneOrMore)
        .Literal("-->");
    

    Ok, but it's your funeral, man.

    Download the library that does this here:
    http://flimflan.com/blog/ReadableRegularExpressions.aspx

    0 讨论(0)
  • 2021-02-20 07:18

    Well, if you had keywords, how would you easily differentiate them from actually matched text? How would you handle whitespace?

    Source text Company: A Dept.: B

    Standard regex:

    Company:\s+(.+)\s+Dept.:\s+(.+)
    

    Or even:

    Company: (.+) Dept. (.+)
    

    Keyword regex (trying really hard not get a strawman...)

    "Company:" whitespace.oneplus group(any.oneplus) whitespace.oneplus "Dept.:" whitespace.oneplus group(any.oneplus)
    

    Or simplified:

    "Company:" space group(any.oneplus) space "Dept.:" space group(any.oneplus)
    

    No, it's probably not better.

    0 讨论(0)
  • 2021-02-20 07:21

    I don't think keywords would give any benefit. Regular expressions as such are complex but also very powerful.

    What I think is more confusing is that every supporting library invents its own syntax instead of using (or extending) the classic Perl regex (e.g. \1, $1, {1}, ... for replacements and many more examples).

    0 讨论(0)
  • 2021-02-20 07:21

    For some reason, my previous answer got deleted. Anyway, i thing ruby regexp machine would fit the bill, at http://www.rubyregexp.sf.net. It is my own project, but i think it should work.

    0 讨论(0)
  • 2021-02-20 07:24

    It's actually pretty easy to implement a "wordier" form of regex -- please see my answer here. In a nutshell: write a handful of functions that return regex strings (and take parameters if necessary).

    0 讨论(0)
  • 2021-02-20 07:30

    I know its answering your question the wrong way around, but RegExBuddy has a feature that explains your regexpression in plain english. This might make it a bit easier to learn.

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