Regular expressions in C # that use Python syntax.

Source: Internet
Author: User

Reprint Please specify source: Http://blog.csdn.net/zxsean


Because of the project requirements, it is now necessary to use Python's regular in C #, and the first approach is IronPython.

But compiling on iOS doesn't work. Fortunately IronPython is an open source project, so get the code to start research.


Because the functionality I need is simple, the final code just determines if the incoming string matches the Python regular expression I passed in.


Parse some of the code directly using:

/* **************************************************************************** * * Copyright (c) Microsoft  Corporation. * * This source code was subject to terms and conditions of the Microsoft public * License. A copy of the license can is found in the license.html file at the * root of this distribution. If You cannot locate the Microsoft public * License, please send a email to [email protected] by using this SOURC E * code in any fashion, you is agreeing to being bound by the terms of the * Microsoft public License. * * You must not remove the this notice, or any other, from this software. * * ***************************************************************************/using System;using System.Text; Using system.text.regularexpressions;///<summary>///python regular parsing//by zealotsean///</summary>public    Static class pythonregex{#region CONSTANTS//short forms//public Static Object I = 0x02;    public static Object L = 0x04; public static Object M = 0x08;    public static Object S = 0x10;    public static Object U = 0x20;    public static Object X = 0x40;    Long forms public static Object IGNORECASE = 0x02;    public static Object LOCALE = 0x04;    public static Object MULTILINE = 0x08;    public static Object dotall = 0x10;    public static Object UNICODE = 0x20;    public static Object VERBOSE = 0x40; #endregion//<summary>///compile a regular expression////</summary>//<param name= "_pattern" ></param&    Gt <returns></returns> public static Python_pattern Compile (string _pattern) {return new Python    _pattern (_pattern, 0, true);    public static bool Ismatched (string _pattern, String _str) {return ismatched (_pattern, _str, 0);  } public static bool Ismatched (string _pattern, string _str, int flags) {return new Python_pattern (_pattern,    Flags). ismatched (_STR); }//<summary>//Compiled Reg-ex pattern///</summary&Gt        public class Python_pattern {internal Regex m_re;        Internal Parsedregex m_pre; Public Python_pattern (String pattern): This (pattern, 0) {} public Python_pattern (string pattern, int flags): This (pattern, flags, false) {} public Python_pattern (string pattern            , int flags, BOOL compiled) {M_pre = Preparseregex (pattern);            RegexOptions opts = flagstooption (flags); This.m_re = new Regex (m_pre. Pattern, opts | (compiled?)        RegexOptions.Compiled:RegexOptions.None)); }///<summary>///Incoming string lookup matches regular expression///</summary>//<param name= "_str" >& lt;/param>//<returns></returns> public bool Ismatched (string _str) {RET Urn M_re. Match (_STR).        Success; The public string Pattern {get {return m_pre.     Userpattern;       }}} private static RegexOptions flagstooption (int flags) {RegexOptions opts = Regexoption        S.none;        if (Flags & (int) IGNORECASE)! = 0) opts |= regexoptions.ignorecase;        if (Flags & (int) MULTILINE)! = 0) opts |= regexoptions.multiline;        if ((Flags & (int) LOCALE) = = 0) opts &= (~regexoptions.cultureinvariant);        if (Flags & (int) dotall)! = 0) opts |= regexoptions.singleline;        if (Flags & (int) VERBOSE)! = 0) opts |= regexoptions.ignorepatternwhitespace;    return opts; } internal class Parsedregex {public Parsedregex (string pattern) {this.        Userpattern = pattern;        } public string Userpattern;        public string Pattern;    Public RegexOptions Options = regexoptions.cultureinvariant; }///<summary>//preparses A regular expression text returning a Parsedregex class//So can be used    For further regular expressions. /// Pass in a python regular expression that returns a C # available format//</summary> private static Parsedregex Preparseregex (string pattern) {        Parsedregex res = new Parsedregex (pattern);        String Newpattern;        int cur = 0, nameindex;        int curgroup = 0;        BOOL Containsnamedgroup = false;        for (;;) {Nameindex = pattern.            IndexOf ("(", cur);                if (Nameindex > 0 && pattern[nameindex-1] = = ' \ \ ') {int curindex = nameIndex-2;                int backslashcount = 1;                    while (curindex >= 0 && pattern[curindex] = = ' \ \ ') {backslashcount++;                curindex--;                }//Odd number of the back slashes, which is a optional//paren that we should ignore.                    if (Backslashcount & 0x01)! = 0) {cur++;                Continue }} IF (Nameindex = =-1) break; if (Nameindex = = pattern.            LENGTH-1) break;                    Switch (Pattern[++nameindex]) {case '? '://EXTENSION syntax if (Nameindex = = pattern.                    LENGTH-1) {return null;                            } switch (Pattern[++nameindex]) {case ' P ':                            Named regex,. NET doesn ' t expect the P so we ' ll remove it; Also, once we see a named group i.e.? P then we need to start artificially//naming all unnamed groups from and on---the IS to g  Et around the fact that//the CLR RegEx support orders all the unnamed groups before all the                            Named//groups, even if the named groups is before the unnamed ones in the pattern; The ArtificiaL naming preserves the order of the groups and thus the order of//The matches if (Nameindex + 1 < pattern. Length && Pattern[nameindex + 1] = = ' = ') {//Match what Ever was previously matched by the named Group//Remove the (? p= pattern = pattern.                                Remove (NameIndex-2, 4); Pattern = pattern.                                Insert (nameIndex-2, "\\\\k<");                                int tmpindex = Nameindex; while (Tmpindex < pattern.                                Length && pattern[tmpindex]! = ') ' tmpindex++; if (Tmpindex = = pattern.                                Length) {return null; } pattern = pattern. Substring (0, Tmpindex) + ">" + pattern.                            Substring (Tmpindex + 1);                                } else {containsnamedgroup = true; Pattern = pattern.                            Remove (Nameindex, 1);                        } break; Case ' I ': Res. Options |= regexoptions.ignorecase;                        Break Case ' L ': Res. Options &= ~ (regexoptions.cultureinvariant);                        Break Case ' m ': Res. Options |= Regexoptions.multiline;                        Break Case ' s ': Res. Options |= Regexoptions.singleline;                        Break                        Case ' u ': break; Case ' x ': Res. Options |= Regexoptions.ignorepatternwhitespace;                        Break Case ': ': break; non-capturing case ' = ': break; Look ahead assertion case ' < ': break;          Positive look behind assertion              Case '! ': break; Negative look ahead assertion case ' # ': break;                        Inline comment case ' ('://yes/no If group exists, we don ' t                            Default: {return null;                }} break;                    Default://Just another group curgroup++;                        if (containsnamedgroup) {//need to name this unnamed group Pattern = pattern.                    Insert (Nameindex, "? <named" + getrandomstring () + ">");            } break;        } cur = nameindex;        } cur = 0;        for (;;) {Nameindex = pattern.            IndexOf (' \ \ ', cur); if (Nameindex = =-1 | | nameindex = = pattern.            LENGTH-1) break; char Curchar = PATtern[++nameindex]; Switch (Curchar) {case ' x ': Case ' u ': Case ' a ': CA                Se ' B ': Case ' e ': Case ' F ': Case ' n ': Case ' R ':                Case ' t ': Case ' V ': Case ' C ': Case ' s ': Case ' W ':                Case ' W ': Case ' P ': Case ' P ': Case ' S ': Case ' d ':                    Case ' D ': Case ' Z '://Known escape sequences, leave escaped.                Break                    Case ' \ \ '://escaping a \ cur + = 2;                Break                    Default:System.Globalization.UnicodeCategory Charclass = char.getunicodecategory (Curchar); Switch (charclass) {//recognized word characterS, always unescape. Case System.Globalization.UnicodeCategory.ModifierLetter:case System.Globalization.UnicodeCategory .                        Lowercaseletter:case System.Globalization.UnicodeCategory.UppercaseLetter: Case System.Globalization.UnicodeCategory.TitlecaseLetter:case System.Globalization.UnicodeCategor Y.otherletter:case System.Globalization.UnicodeCategory.LetterNumber:case System.Globalization.UnicodeCategory.OtherNumber:case System.Globalization.UnicodeCategory.Connect Orpunctuation:pattern = pattern.                            Remove (nameIndex-1, 1);                        Break Case System.Globalization.UnicodeCategory.DecimalDigitNumber://actually don ' t want to Unesca PE ' \1 ', ' \2 ' etc. which is references to groups BreaK            } break;        } cur++; } res.        pattern = pattern;    return res;    } static Random R = new Random (DateTime.Now.Millisecond); private static string getrandomstring () {return R.next (INT32.MAXVALUE/2, Int32.MaxValue).    ToString (); }}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Regular expressions in C # that use Python syntax.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.