Proposal: Regular Expression Pattern Matching #247
Replies: 3 comments
-
If F#, this can be done using active patterns. (Though I think active patterns for regular expressions are not part of the standard library.) Your example would translate to something like: match value with
| Regex @"\d+" numMatch -> …
| Regex @"\s+" wsMatch -> … I imagine that in C#, the same could be done with user-defined switch(value)
{
case Regex(@"\d+", var numMatch): … break;
case Regex(@"\s+", var wsMatch): … break;
} As long as something like this worked, I don't think C# needs special syntax for regular expressions. Though I'm not sure how would this work for compiled regular expressions. |
Beta Was this translation helpful? Give feedback.
-
If I understand the user-defined public class Regex
{
public static bool operator is(string input, string pattern, out Match match)
{ /* ... */ }
public static bool operator is(string input, string pattern, RegexOptions options, out Match match)
{ /* ... */ }
public static bool operator is(string input, string pattern, out MatchCollection matches)
{ /* ... */ }
public static bool operator is(string input, string pattern, RegexOptions options, out MatchCollection matches)
{ /* ... */ }
} While I like the idea of regex in the language (especially to have compile-time validation of its syntax) if the
|
Beta Was this translation helpful? Give feedback.
-
There was some discussion about patterns like this on the Roslyn repo. One of the issues identified was how the parser could disambiguate between input expressions to such patterns v. constant patterns. |
Beta Was this translation helpful? Give feedback.
-
I think this could already be done in a switch leveraging the
when
clause, a static method and anout var
, but there are some limitations. Essentially, existing syntax allows for:That gets pretty wordy (and I can't verify it even works right now as I write this) but I'd envision something more like:
And I know you're probably cringing a bit at that, I am. I'd probably rather not have it than have that syntax. So what I would really envision is two-fold:
This would then move top to bottom (like the other pattern-matching switches) comparing
value
against the regex and dropping into the case where applicable. Some questions for discussion:value
be forced to be astring
, or coerce to a string like in string formatting?Match
to consider, but what about needing aMatchCollection
?Beta Was this translation helpful? Give feedback.
All reactions