System.Text.RegularExpressions.Regex.Matches(string)

Here are the examples of the csharp api System.Text.RegularExpressions.Regex.Matches(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1194 Examples 7

19 Source : StringInjectExtension.cs
with MIT License
from 0x0ade

public static string InjectSingleValue(this string formatString, string key, object replacementValue) {
            string result = formatString;
            //regex replacement of key with value, where the generic key format is:
            //Regex foo = new("{(foo)(?:}|(?::(.[^}]*)}))");
            Regex attributeRegex = new("{(" + key + ")(?:}|(?::(.[^}]*)}))");  //for key = foo, matches {foo} and {foo:SomeFormat}

            //loop through matches, since each key may be used more than once (and with a different format string)
            foreach (Match? m in attributeRegex.Matches(formatString)) {
                if (m == null)
                    continue;

                string replacement = m.ToString();
                if (m.Groups[2].Length > 0) {
                    //matched {foo:SomeFormat}
                    //do a double string.Format - first to build the proper format string, and then to format the replacement value
                    string attributeFormatString = string.Format(CultureInfo.InvariantCulture, "{{0:{0}}}", m.Groups[2]);
                    replacement = string.Format(CultureInfo.CurrentCulture, attributeFormatString, replacementValue);
                } else {
                    //matched {foo}
                    replacement = replacementValue.ToString() ?? string.Empty;
                }
                //perform replacements, one match at a time
                result = result.Replace(m.ToString(), replacement);  //attributeRegex.Replace(result, replacement, 1);
            }
            return result;

        }

19 Source : Chromium.cs
with GNU General Public License v3.0
from 0xfd3

public static byte[] GetMasterKey(string LocalStateFolder)
        {
            //Key saved in Local State file
            string filePath = LocalStateFolder + @"\Local State";
            byte[] masterKey = new byte[] { };

            if (File.Exists(filePath) == false)
                return null;

            //Get key with regex.
            var pattern = new System.Text.RegularExpressions.Regex("\"encrypted_key\":\"(.*?)\"", System.Text.RegularExpressions.RegexOptions.Compiled).Matches(File.ReadAllText(filePath));

            foreach (System.Text.RegularExpressions.Match prof in pattern)
            {
                if (prof.Success)
                    masterKey = Convert.FromBase64String((prof.Groups[1].Value)); //Decode base64
            }

            //Trim first 5 bytes. Its signature "DPAPI"
            byte[] temp = new byte[masterKey.Length - 5];
            Array.Copy(masterKey, 5, temp, 0, masterKey.Length - 5);

            try
            {
                return ProtectedData.Unprotect(temp, null, DataProtectionScope.CurrentUser);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

19 Source : IrdClient.cs
with MIT License
from 13xforever

private static string GetIrdFilename(string html)
        {
            if (string.IsNullOrEmpty(html))
                return null;

            var matches = IrdFilename.Matches(html);
            if (matches.Count == 0)
            {
                Log.Warn("Couldn't parse IRD filename from " + html);
                return null;
            }

            return matches[0].Groups["filename"]?.Value;
        }

19 Source : Machine.cs
with MIT License
from 3RD-Dimension

private void UpdateStatus(string line)
        {
            if (!Connected)
                return;

            if (line.Contains("$J="))
                return;

            if (line.StartsWith("[TLO:"))
            {
                try
                {
                    CurrentTLO = double.Parse(line.Substring(5, line.Length - 6), Constants.DecimalParseFormat);
                    RaiseEvent(PositionUpdateReceived);
                }
                catch { RaiseEvent(NonFatalException, "Error while Parsing Status Message"); }
                return;
            }

            try
            {
                //we use a Regex here so G91.1 etc don't get recognized as G91
                MatchCollection mc = GCodeSplitter.Matches(line);
                for (int i = 0; i < mc.Count; i++)
                {
                    Match m = mc[i];

                    if (m.Groups[1].Value != "G")
                        continue;

                    double code = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);

                    if (code == 17)
                        Plane = ArcPlane.XY;
                    if (code == 18)
                        Plane = ArcPlane.YZ;
                    if (code == 19)
                        Plane = ArcPlane.ZX;

                    if (code == 20)
                        Unit = ParseUnit.Imperial;
                    if (code == 21)
                        Unit = ParseUnit.Metric;

                    if (code == 90)
                        DistanceMode = ParseDistanceMode.Absolute;
                    if (code == 91)
                        DistanceMode = ParseDistanceMode.Incremental;

                    if (code == 49)
                        CurrentTLO = 0;

                    if (code == 43.1)
                    {
                        if (mc.Count > (i + 1))
                        {
                            if (mc[i + 1].Groups[1].Value == "Z")
                            {
                                CurrentTLO = double.Parse(mc[i + 1].Groups[2].Value, Constants.DecimalParseFormat);
                                RaiseEvent(PositionUpdateReceived);
                            }

                            i += 1;
                        }
                    }
                }
            }
            catch { RaiseEvent(NonFatalException, "Error while Parsing Status Message"); }
        }

19 Source : Machine.cs
with MIT License
from 3RD-Dimension

private void ParseStatus(string line)
        {
            MatchCollection statusMatch = StatusEx.Matches(line);

            if (statusMatch.Count == 0)
            {
                NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line));
                return;
            }

            bool posUpdate = false;
            bool overrideUpdate = false;
            bool pinStateUpdate = false;
            bool resetPins = true;

            foreach (Match m in statusMatch)
            {
                if (m.Index == 1)
                {
                    Status = m.Groups[1].Value;
                    continue;
                }

                if (m.Groups[1].Value == "Ov")
                {
                    try
                    {
                        string[] parts = m.Groups[2].Value.Split(',');
                        FeedOverride = int.Parse(parts[0]);
                        RapidOverride = int.Parse(parts[1]);
                        SpindleOverride = int.Parse(parts[2]);
                        overrideUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (m.Groups[1].Value == "WCO")
                {
                    try
                    {
                        string OffsetString = m.Groups[2].Value;

                        if (Properties.Settings.Default.IgnoreAdditionalAxes)
                        {
                            string[] parts = OffsetString.Split(',');
                            if (parts.Length > 3)
                            {
                                Array.Resize(ref parts, 3);
                                OffsetString = string.Join(",", parts);
                            }
                        }

                        WorkOffset = Vector3.Parse(OffsetString);
                        posUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (SyncBuffer && m.Groups[1].Value == "Bf")
                {
                    try
                    {
                        int availableBytes = int.Parse(m.Groups[2].Value.Split(',')[1]);
                        int used = Properties.Settings.Default.ControllerBufferSize - availableBytes;

                        if (used < 0)
                            used = 0;

                        BufferState = used;
                        RaiseEvent(Info, $"Buffer State Synced ({availableBytes} bytes free)");
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (m.Groups[1].Value == "Pn")
                {
                    resetPins = false;

                    string states = m.Groups[2].Value;

                    bool stateX = states.Contains("X");
                    if (stateX != PinStateLimitX)
                        pinStateUpdate = true;
                    PinStateLimitX = stateX;

                    bool stateY = states.Contains("Y");
                    if (stateY != PinStateLimitY)
                        pinStateUpdate = true;
                    PinStateLimitY = stateY;

                    bool stateZ = states.Contains("Z");
                    if (stateZ != PinStateLimitZ)
                        pinStateUpdate = true;
                    PinStateLimitZ = stateZ;

                    bool stateP = states.Contains("P");
                    if (stateP != PinStateProbe)
                        pinStateUpdate = true;
                    PinStateProbe = stateP;
                }

                else if (m.Groups[1].Value == "F")
                {
                    try
                    {
                        FeedRateRealtime = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);
                        posUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (m.Groups[1].Value == "FS")
                {
                    try
                    {
                        string[] parts = m.Groups[2].Value.Split(',');
                        FeedRateRealtime = double.Parse(parts[0], Constants.DecimalParseFormat);
                        SpindleSpeedRealtime = double.Parse(parts[1], Constants.DecimalParseFormat);
                        posUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }
            }

            SyncBuffer = false; //only run this immediately after button press

            //run this later to catch work offset changes before parsing position
            Vector3 NewMachinePosition = MachinePosition;

            foreach (Match m in statusMatch)
            {
                if (m.Groups[1].Value == "MPos" || m.Groups[1].Value == "WPos")
                {
                    try
                    {
                        string PositionString = m.Groups[2].Value;

                        if (Properties.Settings.Default.IgnoreAdditionalAxes)
                        {
                            string[] parts = PositionString.Split(',');
                            if (parts.Length > 3)
                            {
                                Array.Resize(ref parts, 3);
                                PositionString = string.Join(",", parts);
                            }
                        }

                        NewMachinePosition = Vector3.Parse(PositionString);

                        if (m.Groups[1].Value == "WPos")
                            NewMachinePosition += WorkOffset;

                        if (NewMachinePosition != MachinePosition)
                        {
                            posUpdate = true;
                            MachinePosition = NewMachinePosition;
                        }
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

            }

            if (posUpdate && Connected && PositionUpdateReceived != null)
                PositionUpdateReceived.Invoke();

            if (overrideUpdate && Connected && OverrideChanged != null)
                OverrideChanged.Invoke();

            if (resetPins)  //no pin state received in status -> all zero
            {
                pinStateUpdate = PinStateLimitX | PinStateLimitY | PinStateLimitZ | PinStateProbe;  //was any pin set before

                PinStateLimitX = false;
                PinStateLimitY = false;
                PinStateLimitZ = false;
                PinStateProbe = false;
            }

            if (pinStateUpdate && Connected && PinStateChanged != null)
                PinStateChanged.Invoke();

            if (Connected && StatusReceived != null)
                StatusReceived.Invoke(line);
        }

19 Source : GCodeParser.cs
with MIT License
from 3RD-Dimension

static void Parse(string line, int lineNumber)
		{
			MatchCollection matches = GCodeSplitter.Matches(line);

			List<Word> Words = new List<Word>(matches.Count);

			foreach (Match match in matches)
			{
				Words.Add(new Word() { Command = match.Groups[1].Value[0], Parameter = double.Parse(match.Groups[2].Value, Constants.DecimalParseFormat) });
			}

			for (int i = 0; i < Words.Count; i++)
			{
				if (Words[i].Command == 'N')
				{
					Words.RemoveAt(i--);
					continue;
				}

				if (IgnoreAxes.Contains(Words[i].Command) && Properties.Settings.Default.IgnoreAdditionalAxes)
				{
					Words.RemoveAt(i--);
					continue;
				}

				if (!ValidWords.Contains(Words[i].Command))
				{
					Warnings.Add($"ignoring unknown word (letter): \"{Words[i]}\". (line {lineNumber})");
					Words.RemoveAt(i--);
					continue;
				}

				if (Words[i].Command != 'F')
					continue;

				State.Feed = Words[i].Parameter;
				if (State.Unit == ParseUnit.Imperial)
					State.Feed *= 25.4;
				Words.RemoveAt(i--);
				continue;
			}

			for (int i = 0; i < Words.Count; i++)
			{
				if (Words[i].Command == 'M')
				{
					int param = (int)Words[i].Parameter;

					if (param != Words[i].Parameter || param < 0)
						throw new ParseException("M code can only have positive integer parameters", lineNumber);

					Commands.Add(new MCode() { Code = param, LineNumber = lineNumber });

					Words.RemoveAt(i);
					i--;
					continue;
				}

				if (Words[i].Command == 'S')
				{
					double param = Words[i].Parameter;

					if (param < 0)
						Warnings.Add($"spindle speed must be positive. (line {lineNumber})");

					Commands.Add(new Spindle() { Speed = Math.Abs(param), LineNumber = lineNumber });

					Words.RemoveAt(i);
					i--;
					continue;
				}

				if (Words[i].Command == 'G' && !MotionCommands.Contains(Words[i].Parameter))
				{
					#region UnitPlaneDistanceMode

					double param = Words[i].Parameter;

					if (param == 90)
					{
						State.DistanceMode = ParseDistanceMode.Absolute;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 91)
					{
						State.DistanceMode = ParseDistanceMode.Incremental;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 90.1)
					{
						State.ArcDistanceMode = ParseDistanceMode.Absolute;
						Words.RemoveAt(i);
						continue;
					}
					if (param == 91.1)
					{
						State.ArcDistanceMode = ParseDistanceMode.Incremental;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 21)
					{
						State.Unit = ParseUnit.Metric;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 20)
					{
						State.Unit = ParseUnit.Imperial;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 17)
					{
						State.Plane = ArcPlane.XY;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 18)
					{
						State.Plane = ArcPlane.ZX;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 19)
					{
						State.Plane = ArcPlane.YZ;
						Words.RemoveAt(i);
						i--;
						continue;
					}
					if (param == 4)
					{
						if (Words.Count >= 2 && Words[i + 1].Command == 'P')
						{
							if (Words[i + 1].Parameter < 0)
								Warnings.Add($"dwell time must be positive. (line {lineNumber})");

							Commands.Add(new Dwell() { Seconds = Math.Abs(Words[i + 1].Parameter), LineNumber = lineNumber });
							Words.RemoveAt(i + 1);
							Words.RemoveAt(i);
							i--;
							continue;
						}
					}

					Warnings.Add($"ignoring unknown command G{param}. (line {lineNumber})");
					Words.RemoveAt(i--);
					#endregion
				}
			}

			if (Words.Count == 0)
				return;

			int MotionMode = State.LastMotionMode;

			if (Words.First().Command == 'G')
			{
				MotionMode = (int)Words.First().Parameter;
				State.LastMotionMode = MotionMode;
				Words.RemoveAt(0);
			}

			if (MotionMode < 0)
				throw new ParseException("no motion mode active", lineNumber);

			double UnitMultiplier = (State.Unit == ParseUnit.Metric) ? 1 : 25.4;

			Vector3 EndPos = State.Position;

			if (State.DistanceMode == ParseDistanceMode.Incremental && State.PositionValid.Any(isValid => !isValid))
			{
				throw new ParseException("incremental motion is only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
			}

			if ((MotionMode == 2 || MotionMode == 3) && State.PositionValid.Any(isValid => !isValid))
			{
				throw new ParseException("arcs (G2/G3) are only allowed after an absolute position has been established (eg. with \"G90 G0 X0 Y0 Z5\")", lineNumber);
			}

			#region FindEndPos
			{
				int Incremental = (State.DistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'X')
						continue;
					EndPos.X = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.X;
					Words.RemoveAt(i);
					State.PositionValid[0] = true;
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'Y')
						continue;
					EndPos.Y = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Y;
					Words.RemoveAt(i);
					State.PositionValid[1] = true;
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'Z')
						continue;
					EndPos.Z = Words[i].Parameter * UnitMultiplier + Incremental * EndPos.Z;
					Words.RemoveAt(i);
					State.PositionValid[2] = true;
					break;
				}
			}
			#endregion

			if (MotionMode != 0 && State.Feed <= 0)
			{
				throw new ParseException("feed rate undefined", lineNumber);
			}

			if (MotionMode == 1 && State.PositionValid.Any(isValid => !isValid))
			{
				Warnings.Add($"a feed move is used before an absolute position is established, height maps will not be applied to this motion. (line {lineNumber})");
			}

			if (MotionMode <= 1)
			{
				if (Words.Count > 0)
					Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");

				Line motion = new Line();
				motion.Start = State.Position;
				motion.End = EndPos;
				motion.Feed = State.Feed;
				motion.Rapid = MotionMode == 0;
				motion.LineNumber = lineNumber;
				State.PositionValid.CopyTo(motion.PositionValid, 0);

				Commands.Add(motion);
				State.Position = EndPos;
				return;
			}

			double U, V;

			bool IJKused = false;

			switch (State.Plane)
			{
				default:
					U = State.Position.X;
					V = State.Position.Y;
					break;
				case ArcPlane.YZ:
					U = State.Position.Y;
					V = State.Position.Z;
					break;
				case ArcPlane.ZX:
					U = State.Position.Z;
					V = State.Position.X;
					break;
			}

			#region FindIJK
			{
				int ArcIncremental = (State.ArcDistanceMode == ParseDistanceMode.Incremental) ? 1 : 0;

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'I')
						continue;

					switch (State.Plane)
					{
						case ArcPlane.XY:
							U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
							break;
						case ArcPlane.YZ:
							throw new ParseException("current plane is YZ, I word is invalid", lineNumber);
						case ArcPlane.ZX:
							V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.X;
							break;
					}

					IJKused = true;
					Words.RemoveAt(i);
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'J')
						continue;

					switch (State.Plane)
					{
						case ArcPlane.XY:
							V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
							break;
						case ArcPlane.YZ:
							U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Y;
							break;
						case ArcPlane.ZX:
							throw new ParseException("current plane is ZX, J word is invalid", lineNumber);
					}

					IJKused = true;
					Words.RemoveAt(i);
					break;
				}

				for (int i = 0; i < Words.Count; i++)
				{
					if (Words[i].Command != 'K')
						continue;

					switch (State.Plane)
					{
						case ArcPlane.XY:
							throw new ParseException("current plane is XY, K word is invalid", lineNumber);
						case ArcPlane.YZ:
							V = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
							break;
						case ArcPlane.ZX:
							U = Words[i].Parameter * UnitMultiplier + ArcIncremental * State.Position.Z;
							break;
					}

					IJKused = true;
					Words.RemoveAt(i);
					break;
				}
			}
			#endregion

			#region ResolveRadius
			for (int i = 0; i < Words.Count; i++)
			{
				if (Words[i].Command != 'R')
					continue;

				if (IJKused)
					throw new ParseException("both IJK and R notation used", lineNumber);

				if (State.Position == EndPos)
					throw new ParseException("arcs in R-notation must have non-coincident start and end points", lineNumber);

				double Radius = Words[i].Parameter * UnitMultiplier;

				if (Radius == 0)
					throw new ParseException("radius can't be zero", lineNumber);

				double A, B;

				switch (State.Plane)
				{
					default:
						A = EndPos.X;
						B = EndPos.Y;
						break;
					case ArcPlane.YZ:
						A = EndPos.Y;
						B = EndPos.Z;
						break;
					case ArcPlane.ZX:
						A = EndPos.Z;
						B = EndPos.X;
						break;
				}

				A -= U;     //(AB) = vector from start to end of arc along the axes of the current plane
				B -= V;

				//see grbl/gcode.c
				double h_x2_div_d = 4.0 * (Radius * Radius) - (A * A + B * B);
				if (h_x2_div_d < 0)
				{
					throw new ParseException("arc radius too small to reach both ends", lineNumber);
				}

				h_x2_div_d = -Math.Sqrt(h_x2_div_d) / Math.Sqrt(A * A + B * B);

				if (MotionMode == 3 ^ Radius < 0)
				{
					h_x2_div_d = -h_x2_div_d;
				}

				U += 0.5 * (A - (B * h_x2_div_d));
				V += 0.5 * (B + (A * h_x2_div_d));

				Words.RemoveAt(i);
				break;
			}
			#endregion

			if (Words.Count > 0)
				Warnings.Add($"motion command must be last in line (ignoring unused words {string.Join(" ", Words)} in block). (line {lineNumber})");

			Arc arc = new Arc();
			arc.Start = State.Position;
			arc.End = EndPos;
			arc.Feed = State.Feed;
			arc.Direction = (MotionMode == 2) ? ArcDirection.CW : ArcDirection.CCW;
			arc.U = U;
			arc.V = V;
			arc.LineNumber = lineNumber;
			arc.Plane = State.Plane;

			Commands.Add(arc);
			State.Position = EndPos;
			return;
		}

19 Source : GrblCodeTranslator.cs
with MIT License
from 3RD-Dimension

private static void LoadErr(Dictionary<int, string> dict, string path)
		{
			if (!File.Exists(path))
			{
				MainWindow.Logger.Warn("Error Code File Missing: {0}", path);
				return;
			}

			string FileContents;

			try
			{
				FileContents = File.ReadAllText(path);
			}
			catch (Exception ex)
			{
                MainWindow.Logger.Error(ex.Message);
				return;
			}

			Regex LineParser = new Regex(@"""([0-9]+)"",""[^\n\r""]*"",""([^\n\r""]*)""");     //test here https://regex101.com/r/hO5zI1/4

			MatchCollection mc = LineParser.Matches(FileContents);

			foreach (Match m in mc)
			{
				try //shouldn't be needed as regex matched already
				{
					int number = int.Parse(m.Groups[1].Value);

					dict.Add(number, m.Groups[2].Value);
				}
				catch { }
			}
		}

19 Source : GrblCodeTranslator.cs
with MIT License
from 3RD-Dimension

private static void LoadSettings(Dictionary<int, Tuple<string, string, string>> dict, string path)
		{
			if (!File.Exists(path))
			{
                MainWindow.Logger.Warn("GRBL Settings File Missing: {0}", path);
				return;
			}

			string FileContents;

			try
			{
				FileContents = File.ReadAllText(path);
			}
			catch (Exception ex)
			{
                MainWindow.Logger.Error(ex.Message);
				return;
			}

			Regex LineParser = new Regex(@"""([0-9]+)"",""([^\n\r""]*)"",""([^\n\r""]*)"",""([^\n\r""]*)""");

			MatchCollection mc = LineParser.Matches(FileContents);

			foreach (Match m in mc)
			{
				try //shouldn't be needed as regex matched already
				{
					int number = int.Parse(m.Groups[1].Value);

					dict.Add(number, new Tuple<string, string, string>(m.Groups[2].Value, m.Groups[3].Value, m.Groups[4].Value));
				}
				catch { }
			}
		}

19 Source : SendPacket.cs
with MIT License
from 499116344

[Obsolete("请使用BinaryWriter.Write(Richtext)方法。")]
        public static byte[] ConstructMessage(string message)
        {
            var bw = new BinaryWriter(new MemoryStream());
            var r = new Regex(@"([^\[]+)*(\[face\d+\.gif\])([^\[]+)*");
            if (r.IsMatch(message))
            {
                var faces = r.Matches(message);
                for (var i = 0; i < faces.Count; i++)
                {
                    var face = faces[i];
                    for (var j = 1; j < face.Groups.Count; j++)
                    {
                        var group = face.Groups[j].Value;
                        if (group.Contains("[face") && group.Contains(".gif]"))
                        {
                            var faceIndex =
                                Convert.ToByte(group.Substring(5, group.Length - group.LastIndexOf(".") - 4));
                            if (faceIndex > 199)
                            {
                                faceIndex = 0;
                            }

                            //表情
                            bw.Write(new byte[] { 0x02, 0x00, 0x14, 0x01, 0x00, 0x01 });
                            bw.Write(faceIndex);
                            bw.Write(new byte[] { 0xFF, 0x00, 0x02, 0x14 });
                            bw.Write((byte) (faceIndex + 65));
                            bw.Write(new byte[] { 0x0B, 0x00, 0x08, 0x00, 0x01, 0x00, 0x04, 0x52, 0xCC, 0x85, 0x50 });
                        }
                        else if (!string.IsNullOrEmpty(group))
                        {
                            var groupMsg = Encoding.UTF8.GetBytes(group);
                            //普通消息
                            ConstructMessage(bw, groupMsg);
                        }
                    }
                }
            }

            return bw.BaseStream.ToBytesArray();
        }

19 Source : QQUser.cs
with MIT License
from 499116344

public GroupMembers Search_Group_Members(long externalId)
        {
            try
            {
                using (var httpWebClient = new HttpWebClient())
                {
                    var address = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members";
                    var s = $"gc={externalId}&st=0&end=10000&sort=0&bkn={Bkn}";
                    httpWebClient.Headers["Accept"] = "application/json, text/javascript, */*; q=0.01";
                    httpWebClient.Headers["Referer"] = "http://qun.qq.com/member.html";
                    httpWebClient.Headers["X-Requested-With"] = "XMLHttpRequest";
                    httpWebClient.Headers.Add("Cache-Control: no-cache");
                    httpWebClient.Headers["User-Agent"] = _ua;
                    httpWebClient.Cookies = QunCookies;
                    var text = Encoding.UTF8.GetString(httpWebClient.UploadData(address, "POST",
                        Encoding.UTF8.GetBytes(s)));

                    var r = new Regex("\"[0-9]+\":\"[^\"]+\"");
                    if (r.IsMatch(text))
                    {
                        foreach (var match in r.Matches(text))
                        {
                            var str = ((Capture) match).Value.Split(':');
                            var r2 = new Regex("\"[0-9]+\"");
                            var level = r2.Matches(str[0])[0].Value;
                            var r3 = new Regex("\"[^\"]+\"");
                            var name = r3.Matches(str[1])[0].Value;
                            var dataItem = "{\"level\":" + level + ",\"name\":" + name + "}";

                            text = text.Replace(((Capture) match).Value, dataItem);
                        }

                        text = text.Replace("\"levelname\":{", "\"levelname\":[")
                            .Replace("},\"max_count\"", "],\"max_count\"");
                    }

                    MessageLog($"获取群{externalId}成员列表成功:{(text.Length > 200 ? text.Substring(0, 200) : text)}");
                    return JsonConvert.DeserializeObject<GroupMembers>(text);
                }
            }
            catch (Exception ex)
            {
                MessageLog($"获取群{externalId}成员列表失败:{ex.Message}");
            }

            return null;
        }

19 Source : QQUser.cs
with MIT License
from 499116344

public FriendList Get_Friend_List()
        {
            try
            {
                using (var httpWebClient = new HttpWebClient())
                {
                    var address = "https://qun.qq.com/cgi-bin/qun_mgr/get_friend_list";
                    var s = $"bkn={Bkn}";
                    httpWebClient.Headers["Accept"] = "application/json, text/javascript, */*; q=0.01";
                    httpWebClient.Headers["Referer"] = "http://qun.qq.com/member.html";
                    httpWebClient.Headers["X-Requested-With"] = "XMLHttpRequest";
                    httpWebClient.Headers["User-Agent"] = _ua;
                    httpWebClient.Headers.Add("Cache-Control: no-cache");
                    httpWebClient.Cookies = QunCookies;
                    var text = Encoding.UTF8.GetString(httpWebClient.UploadData(address, "POST",
                        Encoding.UTF8.GetBytes(s)));
                    var r = new Regex("\"[0-9]+\":");
                    if (r.IsMatch(text))
                    {
                        foreach (var match in r.Matches(text))
                        {
                            var str = ((Capture) match).Value;
                            text = text.Replace(str, "");
                        }

                        text = text.Replace("\"result\":{{", "\"result\":[{").Replace("\"}}}", "\"}]}");
                    }

                    MessageLog("获取好友列表成功:" + text);
                    return JsonConvert.DeserializeObject<FriendList>(text);
                }
            }
            catch (Exception ex)
            {
                MessageLog("获取好友列表失败:" + ex.Message);
            }

            return null;
        }

19 Source : CommandTree.cs
with MIT License
from 5minlab

public void Run(string commandStr) {
            // Split user input on spaces ignoring anything in qoutes
            Regex regex = new Regex(@""".*?""|[^\s]+");
            MatchCollection matches = regex.Matches(commandStr);
            string[] tokens = new string[matches.Count];
            for (int i = 0; i < tokens.Length; ++i) {
                tokens[i] = matches[i].Value.Replace("\"", "");
            }
            _run(tokens, 0);
        }

19 Source : MacroPatterns.cs
with Apache License 2.0
from aaaddress1

public static string ConvertA1StringToR1C1String(string cellFormula)
        {
            //Remap A1 style references to R1C1 (but ignore anything followed by a " in case its inside an EVALUATE statement)
            string a1pattern = @"([A-Z]{1,2}\d{1,5})";
            Regex rg = new Regex(a1pattern);
            MatchCollection matches = rg.Matches(cellFormula);
            int stringLenChange = 0;

            //Iterate through each match and then replace it at its offset. We iterate through 
            //each case manually to prevent overlapping cases from double replacing - ex: SELECT(B1:B111,B1)
            foreach (var match in matches)
            {
                string matchString = ((Match)match).Value;
                string replaceContent = ExcelHelperClreplaced.ConvertA1ToR1C1(matchString);
                //As we change the string, these indexes will go out of sync, track the size delta to make sure we resync positions
                int matchIndex = ((Match)match).Index + stringLenChange;

                //If the match is followed by a ", then ignore it
                int followingIndex = matchIndex + matchString.Length;
                if (followingIndex < cellFormula.Length && cellFormula[followingIndex] == '"')
                {
                    continue;
                }

                //LINQ replacement for python string slicing
                cellFormula = new string(cellFormula.Take(matchIndex).
                    Concat(replaceContent.ToArray()).
                    Concat(cellFormula.TakeLast(cellFormula.Length - matchIndex - matchString.Length)).ToArray());

                stringLenChange += (replaceContent.Length - matchString.Length);
            }

            return cellFormula;
        }

19 Source : GltfUtility.cs
with Apache License 2.0
from abist-co-ltd

private static List<string> GetGltfMeshPrimitiveAttributes(string jsonString, Regex regex)
        {
            var jsonObjects = new List<string>();

            if (!regex.IsMatch(jsonString))
            {
                return jsonObjects;
            }

            MatchCollection matches = regex.Matches(jsonString);

            for (var i = 0; i < matches.Count; i++)
            {
                jsonObjects.Add(matches[i].Groups["Data"].Captures[0].Value);
            }

            return jsonObjects;
        }

19 Source : GltfUtility.cs
with Apache License 2.0
from abist-co-ltd

private static Dictionary<string, string> GetGltfExtensions(string jsonString, Regex regex)
        {
            var jsonObjects = new Dictionary<string, string>();

            if (!regex.IsMatch(jsonString))
            {
                return jsonObjects;
            }

            var matches = regex.Matches(jsonString);
            var nodeName = string.Empty;

            for (var i = 0; i < matches.Count; i++)
            {
                for (int j = 0; j < matches[i].Groups.Count; j++)
                {
                    for (int k = 0; k < matches[i].Groups[i].Captures.Count; k++)
                    {
                        nodeName = GetGltfNodeName(matches[i].Groups[i].Captures[i].Value);
                    }
                }

                if (!jsonObjects.ContainsKey(nodeName))
                {
                    jsonObjects.Add(nodeName, GetJsonObject(jsonString, matches[i].Index + matches[i].Length));
                }
            }

            return jsonObjects;
        }

19 Source : LanguageCompiler.cs
with MIT License
from ABTSoftware

private static int GetNumberOfCaptures(string regex)
        {
            return numberOfCapturesRegex.Matches(regex).Count;
        }

19 Source : SystemInfo.cs
with MIT License
from Accelerider

private static IReadOnlyDictionary<string, string> GetManagementInfo(string query, Regex regex)
        {
            try
            {
                var result = new ManagementObjectSearcher(new ObjectQuery(query));
                var infoString = string.Empty;
                using (var collection = result.Get())
                {
                    foreach (var item in collection)
                    {
                        var managementObject = item as ManagementObject;
                        infoString = managementObject?.GetText(TextFormat.Mof);
                        if (!string.IsNullOrEmpty(infoString)) break;
                    }
                }

                if (string.IsNullOrEmpty(infoString)) return null;

                return regex.Matches(infoString).OfType<Match>()
                    .Where(item => item.Success)
                    .ToDictionary(item => item.Groups[1].Value, item => item.Groups[2].Value);
            }
            catch (Exception e)
            {
                Logger.Error("An unexpected exception occured while getting management info. ", e);

                return null;
            }
        }

19 Source : LocalizationMessageHelper.cs
with GNU General Public License v3.0
from Acumatica

private bool IsIncorrectStringToFormat()
        {
            Cancellation.ThrowIfCancellationRequested();

            if (!_isFormatMethod)
                return false;

            Optional<object> constString = SemanticModel.GetConstantValue(_messageExpression, Cancellation);
            if (!constString.HasValue)
                return false;

            MatchCollection matchesValue = _formatRegex.Matches(constString.Value as string);

            return matchesValue.Count == 0;
        }

19 Source : ConformanceTests.cs
with MIT License
from adamant

private static List<int> ExpectedCompileErrorLines(CodeFile codeFile, string code)
        {
            return ErrorPattern.Matches(code)
                .Select(match => codeFile.Code.Lines.LineIndexContainingOffset(match.Index) + 1)
                .ToList();
        }

19 Source : ProductAggregationDataAdapter.cs
with MIT License
from Adoxio

private static IEnumerable<Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>> ParseSortExpression(string sortExpression)
		{
			if (string.IsNullOrEmpty(sortExpression))
			{
				return Enumerable.Empty<Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>>();
			}

			return SortExpressionPattern.Matches(sortExpression).Cast<Match>().Select(match =>
			{
				var sortNameCapture = match.Groups["name"].Value;

				Expression<Func<Enreplacedy, object>> sort;

				if (!SortExpressions.TryGetValue(sortNameCapture, out sort))
				{
					return null;
				}

				var sortDirectionCapture = match.Groups["direction"].Value;

				var sortDirection = string.IsNullOrEmpty(sortDirectionCapture) || sortDirectionCapture.StartsWith("a", StringComparison.InvariantCultureIgnoreCase)
					? SortDirection.Ascending
					: SortDirection.Descending;

				return new Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>(sort, sortDirection);

			}).Where(sort => sort != null).ToArray();
		}

19 Source : ReviewAggregationDataAdapter.cs
with MIT License
from Adoxio

private static IEnumerable<Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>> ParseSortExpression(string sortExpression)
		{
			if (string.IsNullOrEmpty(sortExpression))
			{
				return Enumerable.Empty<Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>>();
			}

			return _sortExpressionPattern.Matches(sortExpression).Cast<Match>().Select(match =>
			{
				var sortNameCapture = match.Groups["name"].Value;

				Expression<Func<Enreplacedy, object>> sort;

				if (!SortExpressions.TryGetValue(sortNameCapture, out sort))
				{
					return null;
				}

				var sortDirectionCapture = match.Groups["direction"].Value;

				var sortDirection = string.IsNullOrEmpty(sortDirectionCapture) || sortDirectionCapture.StartsWith("a", StringComparison.InvariantCultureIgnoreCase)
					? SortDirection.Ascending
					: SortDirection.Descending;

				return new Tuple<Expression<Func<Enreplacedy, object>>, SortDirection>(sort, sortDirection);

			}).Where(sort => sort != null).ToArray();
		}

19 Source : ViewSort.cs
with MIT License
from Adoxio

public static IEnumerable<Tuple<string, Direction>> ParseSortExpression(string sortExpression)
		{
			if (string.IsNullOrEmpty(sortExpression))
			{
				return Enumerable.Empty<Tuple<string, Direction>>();
			}

			return SortExpressionPattern.Matches(sortExpression).Cast<Match>().Select(match =>
			{
				var sortNameCapture = match.Groups["name"].Value;

				var sortDirectionCapture = match.Groups["direction"].Value;

				var sortDirection = string.IsNullOrEmpty(sortDirectionCapture) || sortDirectionCapture.StartsWith("a", StringComparison.InvariantCultureIgnoreCase)
					? Direction.Ascending
					: Direction.Descending;

				return new Tuple<string, Direction>(sortNameCapture, sortDirection);

			}).Where(sort => sort != null).ToArray();
		}

19 Source : EpubBuilder.cs
with GNU General Public License v3.0
from Aeroblast

string ProcCSS(string text)
        {
            string r = text;
            Regex reg_link = new Regex("url\\(kindle:flow:([0-9|A-V]+)\\?mime=text/css\\)");
            Regex reg_link2 = new Regex("url\\((kindle:embed:.+?)\\)");
            foreach (Match m in reg_link.Matches(text))
            {
                int flowid = (int)Util.DecodeBase32(m.Groups[1].Value);
                string name = "flow" + Util.Number(flowid) + ".css";
                if (css_names.Find(s => s == name) == null)
                {
                    string csstext = azw3.flows[flowid - 1];
                    csstext = ProcCSS(csstext);
                    csss.Add(csstext);
                    css_names.Add(name);
                    azw3.flowProcessLog[flowid - 1] = name;
                }
                r = r.Replace(m.Groups[0].Value, "url(" + name + ")");
            }
            foreach (Match m in reg_link2.Matches(text))
            {
                r = r.Replace(m.Groups[1].Value, ProcEmbed(m.Groups[1].Value));
            }
            return r;
        }

19 Source : ProviderGuid.cs
with Apache License 2.0
from airbus-cert

public static ProviderGuid Parse(string name)
        {
            var providerGuid = TraceEventProviders.GetProviderGuidByName(name);
            if (providerGuid != Guid.Empty)
            {
                return new ProviderGuid
                {
                    Type = ProviderType.Manifest,
                    Guid = providerGuid
                };
            }
            
            var matches = PATTERN.Matches(name);

            if (matches.Count != 1)
            {
                throw new Exception("Invalid Provider Format");
            }

            GroupCollection matchGroup = matches[0].Groups;

            return new ProviderGuid
            {
                Type = (ProviderType)Enum.Parse(typeof(ProviderType), matchGroup["type"].Value),
                Guid = Guid.Parse(matchGroup["guid"].Value)
            };
        }

19 Source : CancerspaceInspector.cs
with GNU General Public License v3.0
from AkaiMage

public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) {
		if (!initialized) {
			customRenderQueue = (materialEditor.target as Material).shader.renderQueue;
			rng = new System.Random();
			initialized = true;
		}
		cancerfree = (materialEditor.target as Material).shader.name.Contains("Cancerfree");
		
		GUIStyle defaultStyle = new GUIStyle(EditorStyles.foldout);
		defaultStyle.fontStyle = FontStyle.Bold;
		defaultStyle.onNormal = EditorStyles.boldLabel.onNormal;
		defaultStyle.onFocused = EditorStyles.boldLabel.onFocused;
		
		List<CSCategory> categories = new List<CSCategory>();
		categories.Add(new CSCategory(Styles.falloffSettingsreplacedle, defaultStyle, me => {
			CSProperty falloffCurve = FindProperty("_FalloffCurve", props);
			CSProperty falloffDepth = FindProperty("_DepthFalloff", props);
			CSProperty falloffColor = FindProperty("_ColorFalloff", props);
			
			DisplayRegularProperty(me, falloffCurve);
			if (falloffCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_MinFalloff", props));
			DisplayRegularProperty(me, FindProperty("_MaxFalloff", props));
			DisplayRegularProperty(me, falloffDepth);
			if (falloffDepth.prop.floatValue > .5) {
				CSProperty falloffDepthCurve = FindProperty("_DepthFalloffCurve", props);
				
				DisplayRegularProperty(me, falloffDepthCurve);
				if (falloffDepthCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_DepthMinFalloff", props));
				DisplayRegularProperty(me, FindProperty("_DepthMaxFalloff", props));
			}
			DisplayRegularProperty(me, falloffColor);
			if (falloffColor.prop.floatValue > .5) {
				CSProperty falloffColorCurve = FindProperty("_ColorFalloffCurve", props);

				DisplayRegularProperty(me, FindProperty("_ColorChannelForFalloff", props));
				DisplayRegularProperty(me, falloffColorCurve);
				if (falloffColorCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_ColorMinFalloff", props));
				DisplayRegularProperty(me, FindProperty("_ColorMaxFalloff", props));
			}
		}));
		categories.Add(new CSCategory(Styles.particleSystemSettingsreplacedle, defaultStyle, me => {
			CSProperty falloffCurve = FindProperty("_LifetimeFalloffCurve", props);
			CSProperty falloff = FindProperty("_LifetimeFalloff", props);
			
			DisplayRegularProperty(me, FindProperty("_ParticleSystem", props));
			DisplayRegularProperty(me, falloff);
			if (falloff.prop.floatValue > .5) {
				DisplayRegularProperty(me, falloffCurve);
				if (falloffCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_LifetimeMinFalloff", props));
				DisplayRegularProperty(me, FindProperty("_LifetimeMaxFalloff", props));
			}
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.screenShakeSettingsreplacedle, defaultStyle, me => {
			DisplayFloatWithSliderMode(me, FindProperty("_XShake", props));
			DisplayFloatWithSliderMode(me, FindProperty("_YShake", props));
			DisplayFloatWithSliderMode(me, FindProperty("_XShakeSpeed", props));
			DisplayFloatWithSliderMode(me, FindProperty("_YShakeSpeed", props));
			DisplayFloatWithSliderMode(me, FindProperty("_ShakeAmplitude", props));
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.wobbleSettingsreplacedle, defaultStyle, me => {
			DisplayFloatRangeProperty(me, FindProperty("_XWobbleAmount", props));
			DisplayFloatRangeProperty(me, FindProperty("_YWobbleAmount", props));
			DisplayFloatRangeProperty(me, FindProperty("_XWobbleTiling", props));
			DisplayFloatRangeProperty(me, FindProperty("_YWobbleTiling", props));
			DisplayFloatWithSliderMode(me, FindProperty("_XWobbleSpeed", props));
			DisplayFloatWithSliderMode(me, FindProperty("_YWobbleSpeed", props));
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.blurSettingsreplacedle, defaultStyle, me => {
			DisplayFloatWithSliderMode(me, FindProperty("_BlurRadius", props));
			DisplayIntSlider(me, FindProperty("_BlurSampling", props), 1, 5);
			DisplayRegularProperty(me, FindProperty("_AnimatedSampling", props));
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.distortionMapSettingsreplacedle, defaultStyle, me => {
			CSProperty distortionType = FindProperty("_DistortionType", props);
			CSProperty distortionMapRotation = FindProperty("_DistortionMapRotation", props);
			CSProperty distortionAmplitude = FindProperty("_DistortionAmplitude", props);
			CSProperty distortionRotation = FindProperty("_DistortionRotation", props);
			CSProperty distortFlipbook = FindProperty("_DistortFlipbook", props);
			
			DisplayRegularProperty(me, distortionType);
			DisplayRegularProperty(me, FindProperty("_DistortionTarget", props));
			
			switch ((int) distortionType.prop.floatValue) {
				case 0:
					DisplayRegularProperty(me, FindProperty("_BumpMap", props));
					DisplayFloatWithSliderMode(me, distortionMapRotation);
					DisplayFloatWithSliderMode(me, distortionAmplitude);
					DisplayFloatWithSliderMode(me, distortionRotation);
					DisplayFloatWithSliderMode(me, FindProperty("_BumpMapScrollSpeedX", props));
					DisplayFloatWithSliderMode(me, FindProperty("_BumpMapScrollSpeedY", props));
					break;
				case 1:
					DisplayRegularProperty(me, FindProperty("_MeltMap", props));
					DisplayFloatWithSliderMode(me, distortionMapRotation);
					DisplayFloatWithSliderMode(me, distortionAmplitude);
					DisplayFloatWithSliderMode(me, distortionRotation);
					DisplayFloatWithSliderMode(me, FindProperty("_MeltController", props));
					DisplayFloatWithSliderMode(me, FindProperty("_MeltActivationScale", props));
					break;
			}
			
			DisplayRegularProperty(me, distortFlipbook);
			
			if (distortFlipbook.prop.floatValue != 0) {
				DisplayIntField(me, FindProperty("_DistortFlipbookTotalFrames", props));
				DisplayIntField(me, FindProperty("_DistortFlipbookStartFrame", props));
				DisplayIntField(me, FindProperty("_DistortFlipbookRows", props));
				DisplayIntField(me, FindProperty("_DistortFlipbookColumns", props));
				DisplayFloatProperty(me, FindProperty("_DistortFlipbookFPS", props));
			}
				
		}));
		categories.Add(new CSCategory(Styles.overlaySettingsreplacedle, defaultStyle, me => {
			CSProperty overlayImageType = FindProperty("_OverlayImageType", props);
			CSProperty overlayImage = FindProperty("_MainTex", props);
			CSProperty overlayRotation = FindProperty("_MainTexRotation", props);
			CSProperty overlayPixelate = FindProperty("_PixelatedSampling", props);
			CSProperty overlayScrollSpeedX = FindProperty("_MainTexScrollSpeedX", props);
			CSProperty overlayScrollSpeedY = FindProperty("_MainTexScrollSpeedY", props);
			CSProperty overlayBoundary = FindProperty("_OverlayBoundaryHandling", props);
			CSProperty overlayColor = FindProperty("_OverlayColor", props);
			
			if (!cancerfree) BlendModePopup(me, FindProperty("_BlendMode", props));
			
			DisplayRegularProperty(me, overlayImageType);
			switch ((int) overlayImageType.prop.floatValue) {
				// TODO: replace these with proper enums so there's no magic numbers
				case 0:
					DisplayRegularProperty(me, overlayBoundary);
					DisplayRegularProperty(me, overlayPixelate);
					me.TexturePropertySingleLine(Styles.overlayImageText, overlayImage.prop, overlayColor.prop);
					me.TextureScaleOffsetProperty(overlayImage.prop);
					DisplayFloatWithSliderMode(me, overlayRotation);
					if (overlayBoundary.prop.floatValue != 0) {
						DisplayFloatWithSliderMode(me, overlayScrollSpeedX);
						DisplayFloatWithSliderMode(me, overlayScrollSpeedY);
					}
					break;
				case 1:
					DisplayRegularProperty(me, overlayBoundary);
					DisplayRegularProperty(me, overlayPixelate);
					me.TexturePropertySingleLine(Styles.overlayImageText, overlayImage.prop, overlayColor.prop);
					me.TextureScaleOffsetProperty(overlayImage.prop);
					DisplayFloatWithSliderMode(me, overlayRotation);
					if (overlayBoundary.prop.floatValue != 0) {
						DisplayFloatWithSliderMode(me, overlayScrollSpeedX);
						DisplayFloatWithSliderMode(me, overlayScrollSpeedY);
					}
					DisplayIntField(me, FindProperty("_FlipbookTotalFrames", props));
					DisplayIntField(me, FindProperty("_FlipbookStartFrame", props));
					DisplayIntField(me, FindProperty("_FlipbookRows", props));
					DisplayIntField(me, FindProperty("_FlipbookColumns", props));
					DisplayFloatProperty(me, FindProperty("_FlipbookFPS", props));
					break;
				case 2:
					DisplayRegularProperty(me, FindProperty("_OverlayCubemap", props));
					DisplayColorProperty(me, overlayColor);
					DisplayVec3WithSliderMode(
						me,
						"Rotation",
						FindProperty("_OverlayCubemapRotationX", props),
						FindProperty("_OverlayCubemapRotationY", props),
						FindProperty("_OverlayCubemapRotationZ", props)
					);
					DisplayVec3WithSliderMode(
						me,
						"Rotation Speed",
						FindProperty("_OverlayCubemapSpeedX", props),
						FindProperty("_OverlayCubemapSpeedY", props),
						FindProperty("_OverlayCubemapSpeedZ", props)
					);
					break;
			}
			
			DisplayFloatRangeProperty(me, FindProperty("_BlendAmount", props));
		}));
		if (cancerfree) categories.Add(new CSCategory(Styles.blendSettingsreplacedle, defaultStyle, me => {
			DisplayRegularProperty(me, FindProperty("_BlendOp", props));
			DisplayRegularProperty(me, FindProperty("_BlendSource", props));
			DisplayRegularProperty(me, FindProperty("_BlendDestination", props));
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.screenColorAdjustmentsreplacedle, defaultStyle, me => {
			CSProperty colorBurningToggle = FindProperty("_Burn", props);
			
			DisplayVec3WithSliderMode(
				me,
				"HSV Add",
				FindProperty("_HueAdd", props),
				FindProperty("_SaturationAdd", props),
				FindProperty("_ValueAdd", props)
			);
			DisplayVec3WithSliderMode(
				me,
				"HSV Multiply",
				FindProperty("_HueMultiply", props),
				FindProperty("_SaturationMultiply", props),
				FindProperty("_ValueMultiply", props)
			);
			
			DisplayFloatRangeProperty(me, FindProperty("_InversionAmount", props));
			DisplayColorProperty(me, FindProperty("_Color", props));
			
			BlendModePopup(me, FindProperty("_ScreenColorBlendMode", props));
			
			DisplayRegularProperty(me, colorBurningToggle);
			if (colorBurningToggle.prop.floatValue == 1) {
				DisplayFloatRangeProperty(me, FindProperty("_BurnLow", props));
				DisplayFloatRangeProperty(me, FindProperty("_BurnHigh", props));
			}
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.screenTransformreplacedle, defaultStyle, me => {
			DisplayRegularProperty(me, FindProperty("_ScreenBoundaryHandling", props));
			DisplayRegularProperty(me, FindProperty("_ScreenReprojection", props));
			DisplayFloatWithSliderMode(me, FindProperty("_Zoom", props));
			DisplayRegularProperty(me, FindProperty("_Pixelation", props));
			
			CSProperty screenXOffsetR = FindProperty("_ScreenXOffsetR", props);
			CSProperty screenXOffsetG = FindProperty("_ScreenXOffsetG", props);
			CSProperty screenXOffsetB = FindProperty("_ScreenXOffsetB", props);
			CSProperty screenXOffsetA = FindProperty("_ScreenXOffsetA", props);
			CSProperty screenYOffsetR = FindProperty("_ScreenYOffsetR", props);
			CSProperty screenYOffsetG = FindProperty("_ScreenYOffsetG", props);
			CSProperty screenYOffsetB = FindProperty("_ScreenYOffsetB", props);
			CSProperty screenYOffsetA = FindProperty("_ScreenYOffsetA", props);
			CSProperty screenXMultiplierR = FindProperty("_ScreenXMultiplierR", props);
			CSProperty screenXMultiplierG = FindProperty("_ScreenXMultiplierG", props);
			CSProperty screenXMultiplierB = FindProperty("_ScreenXMultiplierB", props);
			CSProperty screenXMultiplierA = FindProperty("_ScreenXMultiplierA", props);
			CSProperty screenYMultiplierR = FindProperty("_ScreenYMultiplierR", props);
			CSProperty screenYMultiplierG = FindProperty("_ScreenYMultiplierG", props);
			CSProperty screenYMultiplierB = FindProperty("_ScreenYMultiplierB", props);
			CSProperty screenYMultiplierA = FindProperty("_ScreenYMultiplierA", props);
			
			if (sliderMode) {
				DisplayFloatRangeProperty(me, screenXOffsetA);
				DisplayFloatRangeProperty(me, screenYOffsetA);
				DisplayFloatRangeProperty(me, screenXOffsetR);
				DisplayFloatRangeProperty(me, screenYOffsetR);
				DisplayFloatRangeProperty(me, screenXOffsetG);
				DisplayFloatRangeProperty(me, screenYOffsetG);
				DisplayFloatRangeProperty(me, screenXOffsetB);
				DisplayFloatRangeProperty(me, screenYOffsetB);
				DisplayFloatRangeProperty(me, screenXMultiplierA);
				DisplayFloatRangeProperty(me, screenYMultiplierA);
				DisplayFloatRangeProperty(me, screenXMultiplierR);
				DisplayFloatRangeProperty(me, screenYMultiplierR);
				DisplayFloatRangeProperty(me, screenXMultiplierG);
				DisplayFloatRangeProperty(me, screenYMultiplierG);
				DisplayFloatRangeProperty(me, screenXMultiplierB);
				DisplayFloatRangeProperty(me, screenYMultiplierB);
			} else {
				DisplayVec4Field(me, "Screen X Offset (RGB)", screenXOffsetR, screenXOffsetG, screenXOffsetB, screenXOffsetA);
				DisplayVec4Field(me, "Screen Y Offset (RGB)", screenYOffsetR, screenYOffsetG, screenYOffsetB, screenYOffsetA);
				DisplayVec4Field(me, "Screen X Multiplier (RGB)", screenXMultiplierR, screenXMultiplierG, screenXMultiplierB, screenXMultiplierA);
				DisplayVec4Field(me, "Screen Y Multiplier (RGB)", screenYMultiplierR, screenYMultiplierG, screenYMultiplierB, screenYMultiplierA);
			}
			DisplayFloatRangeProperty(me, FindProperty("_ScreenRotationAngle", props));
		}));
		categories.Add(new CSCategory(Styles.targetObjectSettingsreplacedle, defaultStyle, me => {
			DisplayVec4Field(
				me,
				"Position",
				FindProperty("_ObjectPositionX", props),
				FindProperty("_ObjectPositionY", props),
				FindProperty("_ObjectPositionZ", props),
				FindProperty("_ObjectPositionA", props)
			);
			DisplayVec3Field(
				me,
				"Rotation",
				FindProperty("_ObjectRotationX", props),
				FindProperty("_ObjectRotationY", props),
				FindProperty("_ObjectRotationZ", props)
			);
			DisplayVec4Field(
				me,
				"Scale",
				FindProperty("_ObjectScaleX", props),
				FindProperty("_ObjectScaleY", props),
				FindProperty("_ObjectScaleZ", props),
				FindProperty("_ObjectScaleA", props)
			);
			DisplayRegularProperty(me, FindProperty("_Puffiness", props));
		}));
		categories.Add(new CSCategory(Styles.stencilreplacedle, defaultStyle, me => {
			DisplayIntSlider(me, FindProperty("_StencilRef", props), 0, 255);
			DisplayRegularProperty(me, FindProperty("_StencilComp", props));
			DisplayRegularProperty(me, FindProperty("_StencilPreplacedOp", props));
			DisplayRegularProperty(me, FindProperty("_StencilFailOp", props));
			DisplayRegularProperty(me, FindProperty("_StencilZFailOp", props));
			DisplayIntSlider(me, FindProperty("_StencilReadMask", props), 0, 255);
			DisplayIntSlider(me, FindProperty("_StencilWriteMask", props), 0, 255);
		}));
		categories.Add(new CSCategory(Styles.maskingreplacedle, defaultStyle, me => {
			if (!cancerfree) {
				DisplayRegularProperty(me, FindProperty("_DistortionMask", props));
				DisplayFloatRangeProperty(me, FindProperty("_DistortionMaskOpacity", props));
			}
			
			DisplayRegularProperty(me, FindProperty("_OverlayMask", props));
			DisplayFloatRangeProperty(me, FindProperty("_OverlayMaskOpacity", props));
			
			DisplayRegularProperty(me, FindProperty("_OverallEffectMask", props));
			DisplayFloatRangeProperty(me, FindProperty("_OverallEffectMaskOpacity", props));
			BlendModePopup(me, FindProperty("_OverallEffectMaskBlendMode", props));

			EditorGUILayout.Space();
			
			DisplayRegularProperty(me, FindProperty("_OverallAmplitudeMask", props));
			DisplayFloatRangeProperty(me, FindProperty("_OverallAmplitudeMaskOpacity", props));
		}));
		categories.Add(new CSCategory(Styles.miscSettingsreplacedle, defaultStyle, me => {
			DisplayRegularProperty(me, FindProperty("_CullMode", props));
			DisplayRegularProperty(me, FindProperty("_ZTest", props));
			DisplayRegularProperty(me, FindProperty("_ZWrite", props));
			ShowColorMaskFlags(me, FindProperty("_ColorMask", props));
			DisplayRegularProperty(me, FindProperty("_MirrorMode", props));
			DisplayRegularProperty(me, FindProperty("_EyeSelector", props));
			DisplayRegularProperty(me, FindProperty("_PlatformSelector", props));
			CSProperty projectionType = FindProperty("_ProjectionType", props);
			DisplayRegularProperty(me, projectionType);
			if (projectionType.prop.floatValue != 2) {
				DisplayVec3WithSliderMode(
					me,
					Styles.projectionRotationText,
					FindProperty("_ProjectionRotX", props),
					FindProperty("_ProjectionRotY", props),
					FindProperty("_ProjectionRotZ", props)
				);
			}
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.renderQueueExportreplacedle, defaultStyle, me => {
			Material material = me.target as Material;
			
			customRenderQueue = EditorGUILayout.IntSlider(Styles.customRenderQueueSliderText, customRenderQueue, 0, 5000);
			if (GUILayout.Button(Styles.exportCustomRenderQueueButtonText)) {
				int relativeQueue = customRenderQueue - ((int) UnityEngine.Rendering.RenderQueue.Transparent);
				string newQueueString = "Transparent" + (relativeQueue >= 0 ? "+" : "") + relativeQueue;
				string shaderName = "RedMage/Cancer" + (cancerfree ? "free" : "space");
				string newShaderPath = shaderName + " Queue " + customRenderQueue;
				
				string shaderPath = replacedetDatabase.GetreplacedetPath(material.shader.GetInstanceID());
				string outputLocation = shaderPath.Substring(0, shaderPath.Replace("\\", "/").LastIndexOf('/') + 1) + "CancerspaceQueue" + customRenderQueue + ".shader";
				
				try {
					using (StreamWriter sw = new StreamWriter(outputLocation)) {
						using (StreamReader sr = new StreamReader(shaderPath)) {
							string line;
							while ((line = sr.ReadLine()) != null) {
								if (line.Contains("\"Transparent+")) {
									Regex rx = new Regex(@"Transparent[+-]\d+", RegexOptions.Compiled);
									MatchCollection matches = rx.Matches(line);
									foreach (Match match in matches) {
										line = line.Replace(match.Value, newQueueString);
									}
								} else if (line.Contains(shaderName)) {
									Regex rx = new Regex("\"[^\"]+\"", RegexOptions.Compiled);
									MatchCollection matches = rx.Matches(line);
									foreach (Match match in matches) {
										line = line.Replace(match.Value, "\"" + newShaderPath + "\"");
									}
								}
								if (!cancerfree) line = line.Replace("_Garb", "_Garb" + customRenderQueue);
								sw.Write(line);
								sw.WriteLine();
							}
						}
					}
				} catch (Exception e) {
					Debug.Log("AAAGAGHH WHAT? HOW? WHY??? WHAT ARE YOU DOING? Shader file could not be read / written.");
					Debug.Log(e.Message);
					return;
				}
				
				replacedetDatabase.Refresh();
				
				material.shader = Shader.Find(newShaderPath);
				
				replacedetDatabase.Savereplacedets();
			}
		}));
		
		EditorGUIUtility.labelWidth = 0f;
		
		sliderMode = EditorGUILayout.ToggleLeft(Styles.sliderModeCheckboxText, sliderMode);
		showRandomizerOptions = EditorGUILayout.ToggleLeft(Styles.randomizerOptionsCheckboxText, showRandomizerOptions);
		if (showRandomizerOptions) {
			randomizingCurrentPreplaced = GUILayout.Button("Randomize Values");
		}
		
		int oldflags = GetExpansionFlags();
		int newflags = 0;
		for (int i = 0; i < categories.Count; ++i) {
			bool expanded = EditorGUILayout.Foldout((oldflags & (1 << i)) != 0, categories[i].name, true, categories[i].style);
			newflags |= (expanded ? 1 : 0) << i;
			if (expanded) {
				EditorGUI.indentLevel++;
				categories[i].setupDelegate(materialEditor);
				EditorGUI.indentLevel--;
			}
		}
		SetExpansionFlags(newflags);
		
		
		if (!cancerfree) GUI.enabled = false;
		materialEditor.RenderQueueField();
		
		randomizingCurrentPreplaced = false;
	}

19 Source : LogEntry.cs
with Apache License 2.0
from alaatm

List<TextSpan> ExtractSpans()
        {
            var spans = new List<TextSpan>();
            var current = 0;

            foreach (Match m in _propRegex.Matches(MessageTemplate))
            {
                var prop = m.Groups[0].Value;
                var name = m.Groups[1].Value;
                name = name.Contains(':') ? name.Substring(0, name.IndexOf(':')) : name;

                var value = Properties.FirstOrDefault(p => p.Name == name)?.Value;

                var startIdx = MessageTemplate.IndexOf(prop, current);
                var endIdx = startIdx + prop.Length;
                var section = MessageTemplate.Substring(current, startIdx - current);

                spans.Add(new TextSpan
                {
                    Text = section,
                });

                if (!string.IsNullOrEmpty(value))
                {
                    var isNumber = double.TryParse(value, out var _);
                    spans.Add(new TextSpan
                    {
                        Kind = isNumber ? "num" : "str",
                        Text = value,
                    });
                }
                else
                {
                    spans.Add(new TextSpan
                    {
                        Text = prop,
                    });
                }

                current = endIdx;
            }

            spans.Add(new TextSpan
            {
                Text = MessageTemplate.Substring(current),
            });

            var result = spans.Where(p => !string.IsNullOrEmpty(p.Text)).ToList();
            return result;
        }

19 Source : AutoComputeShaderNodeView.cs
with MIT License
from alelievr

void UpdateComputeShaderData(ComputeShader shader)
		{
			if (ShaderUtil.GetComputeShaderMessages(shader).Any(m => m.severity == ShaderCompilerMessageSeverity.Error))
			{
				Debug.LogError("Compute Shader " + shader + " has errors");
				return;
			}

			var path = replacedetDatabase.GetreplacedetPath(shader);
			string fileContent = File.ReadAllText(path);

			// First remove all the functions from the text
			int functionMarkLocation = fileContent.IndexOf("{");
			fileContent = fileContent.Substring(0, functionMarkLocation).Trim();

			// Fill kernel names
			computeShaderNode.kernelNames.Clear();
			foreach (Match match in kernelRegex.Matches(fileContent))
				computeShaderNode.kernelNames.Add(match.Groups[1].Value);
			
			// Fill output properties name
			computeShaderNode.computeOutputs.Clear();
			foreach (Match match in readWriteObjects.Matches(fileContent))
			{
				if (match.Groups[4].Value.StartsWith("__"))
					continue;
				
				if (match.Groups[4].Value == computeShaderNode.previewTexturePropertyName)
					continue;

				computeShaderNode.computeOutputs.Add(new AutoComputeShaderNode.ComputeParameter{
					displayName = ObjectNames.NicifyVariableName(match.Groups[4].Value),
					propertyName = match.Groups[4].Value,
					specificType = match.Groups[3].Value,
					sType = new SerializableType(ComputeShaderTypeToCSharp(match.Groups[2].Value)),
				});
			}

			// We can then select input properties
			computeShaderNode.computeInputs.Clear();
			foreach (Match match in readOnlyObjects.Matches(fileContent))
			{
				var propertyName = match.Groups[4].Value;

				if (propertyName.StartsWith("__"))
					continue;

				if (propertyName == computeShaderNode.previewTexturePropertyName)
					continue;

				// If the resource is allocated by this node, we don't display it as input
				if (computeShaderNode.managedResources.Any(r => r.propertyName == propertyName && r.autoAlloc))
					continue;

				computeShaderNode.computeInputs.Add(new AutoComputeShaderNode.ComputeParameter{
					displayName = ObjectNames.NicifyVariableName(match.Groups[4].Value),
					propertyName = match.Groups[4].Value,
					specificType = match.Groups[3].Value,
					sType = new SerializableType(ComputeShaderTypeToCSharp(match.Groups[2].Value)),
				});
			}

			UpdateAllocUI();

			computeShaderNode.UpdateComputeShader();
		}

19 Source : MethodHelper.cs
with MIT License
from AlenToma

internal static ISqlCommand ProcessSql(this IRepository repository, TransactionSqlConnection connection, IDbTransaction tran, string sql)
        {
            var i = 1;
            var dicCols = new SafeValueType<string, Tuple<object, SqlDbType>>();
            MatchCollection matches = null;
            while ((matches = stringExp.Matches(sql)).Count > 0)
            {
                var exp = matches[0];
                var col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"String\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                var v = str.ConvertValue<string>();
                if (string.Equals(v, "null", StringComparison.OrdinalIgnoreCase))
                    v = null;
                dicCols.TryAdd(col, new Tuple<object, SqlDbType>(v, SqlDbType.NVarChar));
                i++;
            }

            while ((matches = dateExp.Matches(sql)).Count > 0)
            {
                var exp = matches[0];
                var col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"Date\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<DateTime?>(), SqlDbType.DateTime));
                i++;
            }

            while ((matches = guidExp.Matches(sql)).Count > 0)
            {
                var exp = matches[0];
                var col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"Guid\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<Guid?>(), SqlDbType.UniqueIdentifier));
                i++;
            }


            while ((matches = decimalExp.Matches(sql)).Count > 0)
            {
                var exp = matches[0];
                var col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"Decimal\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<decimal?>(), SqlDbType.Decimal));
                i++;
            }

            sql = sql.CleanValidSqlName(repository.DataBaseTypes);
            DbCommand cmd = null;

            try
            {
                switch (repository.DataBaseTypes)
                {
                    case DataBaseTypes.Mssql:
                        cmd = tran != null ?
                            "System.Data.SqlClient.SqlCommand".GetObjectType("System.Data.SqlClient").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
                                  "System.Data.SqlClient.SqlCommand".GetObjectType("System.Data.SqlClient").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
                        break;

                    case DataBaseTypes.PostgreSql:
                        cmd = tran != null ?
                           "Npgsql.NpgsqlCommand".GetObjectType("Npgsql").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
                                 "Npgsql.NpgsqlCommand".GetObjectType("Npgsql").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
                        break;

                    case DataBaseTypes.Sqllight:
                        cmd = tran != null ?
                             "System.Data.SQLite.SQLiteCommand".GetObjectType("System.Data.SQLite").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
                                   "System.Data.SQLite.SQLiteCommand".GetObjectType("System.Data.SQLite").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
                        break;
                }
            }
            catch (Exception e)
            {
                switch (repository.DataBaseTypes)
                {
                    case DataBaseTypes.Mssql:
                        throw new EnreplacedyException($"Please make sure that nuget 'System.Data.SqlClient' is installed \n orginal exception: \n {e.Message}");

                    case DataBaseTypes.PostgreSql:
                        throw new EnreplacedyException($"Please make sure that nuget 'Npgsql' is installed \n orginal exception: \n {e.Message}");

                    case DataBaseTypes.Sqllight:
                        throw new EnreplacedyException($"Please make sure that nuget 'System.Data.SQLite' is installed \n orginal exception: \n {e.Message}");
                }
            }

            var dbCommandExtended = new DbCommandExtended(cmd, repository);
            foreach (var dic in dicCols)
            {
                dbCommandExtended.AddInnerParameter(dic.Key, dic.Value.Item1);

            }
            return dbCommandExtended;
        }

19 Source : LinqToSql.cs
with MIT License
from AlenToma

private string CleanText(string replaceWith = null)
        {
            MatchCollection matches = null;
            var result = "";
            while ((matches = StringyFyExp.Matches(sb.ToString())).Count > 0)
            {
                var exp = matches[0];

                result = exp.Value.Replace("</Stringify>", "").TrimEnd(']').Substring(@"<Stringify>\[".Length - 1);
                sb = sb.Remove(exp.Index, exp.Value.Length);
                if (replaceWith != null)
                    sb = sb.Insert(exp.Index, replaceWith);

            }
            return result;
        }

19 Source : LinqToSql.cs
with MIT License
from AlenToma

internal void CleanDecoder(string replaceWith)
        {
            if (!EndWithDecoder())
                sb.Append(replaceWith);
            else
            {
                MatchCollection matches = null;
                var result = new string[0];
                while ((matches = DataEncodeExp.Matches(sb.ToString())).Count > 0)
                {
                    var m = matches[0];
                    result = m.Value.Replace("</DataEncode>", "").TrimEnd(']').Substring(@"<DataEncode>\[".Length - 1).Split('|'); // get the key
                    sb = sb.Remove(m.Index, m.Value.Length);
                    if (replaceWith.Contains("String["))
                    {
                        var spt = replaceWith.Split(new string[] { "]," }, StringSplitOptions.None).Where(x => !string.IsNullOrEmpty(x));
                        var i = 0;
                        var value = "";
                        foreach (var str in spt)
                        {
                            i++;
                            var xValue = str.Trim().Replace("String[", "").TrimEnd("]");
                            var rValue = xValue.TrimStart('%').TrimEnd("%");
                            var codedValue = new DataCipher(result.First(), result.Last().ConvertValue<int>().ConvertValue<DataCipherKeySize>()).Encrypt(rValue);
                            if (xValue.StartsWith("%"))
                                codedValue = "%" + codedValue;
                            if (xValue.EndsWith("%"))
                                codedValue += "%";
                            value += $"String[{codedValue}]{(i == spt.Count() ? "" : ",")}";
                        }
                        sb.Insert(m.Index, value);
                    }
                    else if (replaceWith.Contains("Date["))
                    {
                        var spt = replaceWith.Split(new string[] { "]," }, StringSplitOptions.None).Where(x => !string.IsNullOrEmpty(x));
                        var i = 0;
                        var value = "";
                        foreach (var str in spt)
                        {
                            i++;
                            var xValue = str.Trim().Replace("Date[", "").TrimEnd("]");
                            var rValue = xValue.TrimStart('%').TrimEnd("%");
                            var codedValue = new DataCipher(result.First(), result.Last().ConvertValue<int>().ConvertValue<DataCipherKeySize>()).Encrypt(rValue);
                            if (xValue.StartsWith("%"))
                                codedValue = "%" + codedValue;
                            if (xValue.EndsWith("%"))
                                codedValue += "%";
                            value += $"Date[{codedValue}]{(i == spt.Count() ? "" : ",")}";
                        }
                        sb.Insert(m.Index, value);
                    }
                    else
                        sb = sb.Insert(m.Index, new DataCipher(result.First(), result.Last().ConvertValue<int>().ConvertValue<DataCipherKeySize>()).Encrypt(replaceWith));

                }
            }
        }

19 Source : LinqToSql.cs
with MIT License
from AlenToma

private void validateBinaryExpression(BinaryExpression b, Expression exp)
        {
            if (b != null && exp != null)
            {

                var StringifyText = StringyFyExp.Matches(sb.ToString()).Cast<Match>().FirstOrDefault();
                var isEnum = StringifyText != null;
                if ((exp.NodeType == ExpressionType.MemberAccess || exp.NodeType == ExpressionType.Not)
                    && b.NodeType != ExpressionType.Equal
                    && b.NodeType != ExpressionType.NotEqual && (exp.Type == typeof(bool) || exp.Type == typeof(bool?)))
                {
                    if (exp.NodeType != ExpressionType.Not)
                        sb.Append(" = " + (DataBaseTypes == DataBaseTypes.PostgreSql ? "true" : "1"));
                    else
                        sb.Append(" = " + (DataBaseTypes == DataBaseTypes.PostgreSql ? "false" : "0"));
                }
            }
            else
            {
                MatchCollection matches = BoolExp.Matches(sb.ToString());
                var result = "";
                var i = 0;
                var length = matches.Count - 1;
                while ((matches = BoolExp.Matches(sb.ToString())).Count > 0)
                {

                    var m = matches[0];
                    result = m.Value.Replace("</bool>", "").TrimEnd(']').Substring(@"<bool>\[".Length - 1);
                    var addValue = m.Index + boolString.Length + 3 <= sb.Length ? sb.ToString().Substring(m.Index, boolString.Length + 3) : string.Empty;
                    sb = sb.Remove(m.Index, m.Value.Length);
                    if (!addValue.Contains("="))
                    {
                        var value = result.Replace("T", "");
                        var add = result.Contains("T");
                        if ((b == null || i < length || m.Index + m.Value.Length < sb.ToString().Length - 1))
                            sb = sb.Insert(m.Index, (!add ? " = " : "") + (value.ConvertValue<int>() == 0 ? DataBaseTypes == DataBaseTypes.PostgreSql ? "false" : "0" : DataBaseTypes == DataBaseTypes.PostgreSql ? "true" : "1"));
                    }
                    i++;
                }
            }
        }

19 Source : LinqToSql.cs
with MIT License
from AlenToma

protected Expression VisitConstantFixed(ConstantExpression c, string memName = "")
        {
            IQueryable q = c.Value as IQueryable;
            var StringifyText = StringyFyExp.Matches(sb.ToString()).Cast<Match>().FirstOrDefault();
            var isEnum = StringifyText != null;
            string type = null;
            if (isEnum)
                type = CleanText();
            if (q == null && c.Value == null)
            {
                sb.Append("NULL");
            }
            else if (q == null)
            {
                switch (Type.GetTypeCode(c.Value.GetType()))
                {
                    case TypeCode.Boolean:
                        sb.Append(((bool)c.Value) ? (DataBaseTypes == DataBaseTypes.PostgreSql ? "true" : "1") : (DataBaseTypes == DataBaseTypes.PostgreSql ? "false" : "0"));
                        break;

                    case TypeCode.String:
                        CleanDecoder(string.Format("String[{0}]", c.Value));
                        break;

                    case TypeCode.DateTime:
                        CleanDecoder(string.Format("Date[{0}]", c.Value));
                        break;

                    case TypeCode.Object:

                        object value = null;
                        Type fieldType = null;
                        if (c.Value.GetType().GetFields(_bindingFlags).Length > 0 && (string.IsNullOrEmpty(memName) || c.Value.GetType().GetFields(_bindingFlags).Any(x => x.Name == memName)))
                        {
                            var field = string.IsNullOrEmpty(memName)
                                 ? c.Value.GetType().GetFields(_bindingFlags).FirstOrDefault()
                                 : c.Value.GetType().GetFields(_bindingFlags).FirstOrDefault(x => x.Name == memName);
                            fieldType = field?.FieldType;

                            value = field?.GetValue(c.Value);

                        }
                        else
                        {
                            var field = string.IsNullOrEmpty(memName)
                            ? c.Value.GetType().GetProperties().FirstOrDefault()
                            : c.Value.GetType().GetProperties().FirstOrDefault(x => x.Name == memName);
                            fieldType = field?.PropertyType;
                            value = field?.GetValue(c.Value);
                        }



                        if (value == null && fieldType == null)
                            break;
                        CleanDecoder(ValuetoSql(value, isEnum, fieldType));
                        break;
                    default:
                        if (isEnum && SavedTypes.ContainsKey(type))
                        {
                            var enumtype = SavedTypes[type];
                            var v = c.Value.ConvertValue(enumtype);
                            CleanDecoder(ValuetoSql(v, isEnum));
                            break;
                        }
                        CleanDecoder(ValuetoSql(c.Value, isEnum));
                        break;
                }
            }

            return c;
        }

19 Source : LinqToSql.cs
with MIT License
from AlenToma

protected override Expression VisitBinary(BinaryExpression b)
        {
            sb.Append("(");
            this.Visit(b.Left);
            var StringifyText = StringyFyExp.Matches(sb.ToString()).Cast<Match>().FirstOrDefault();
            var isEnum = StringifyText != null;
            validateBinaryExpression(b, b.Left);
            switch (b.NodeType)
            {
                case ExpressionType.And:
                    sb.Append(" AND ");
                    break;

                case ExpressionType.AndAlso:
                    sb.Append(" AND ");
                    break;

                case ExpressionType.Or:
                case ExpressionType.OrElse:
                    sb.Append(" OR ");
                    break;

                case ExpressionType.Equal:
                    if (IsNullConstant(b.Right))
                    {
                        if (isEnum)
                        {
                            CleanText();
                            InsertBeforeDecoder(" IS ");
                            InsertBeforeDecoder(StringifyText.ToString());
                        }
                        else
                            CleanDecoder(" IS ");
                    }
                    else
                    {
                        if (isEnum)
                        {
                            CleanText();
                            InsertBeforeDecoder(" = ");
                            InsertBeforeDecoder(StringifyText.ToString());
                        }
                        else
                            InsertBeforeDecoder(" = ");
                    }
                    break;

                case ExpressionType.NotEqual:
                    if (IsNullConstant(b.Right))
                    {
                        if (isEnum)
                        {
                            CleanText();
                            InsertBeforeDecoder(" IS NOT ");
                            InsertBeforeDecoder(StringifyText.ToString());
                        }
                        else
                            InsertBeforeDecoder(" IS NOT ");

                    }
                    else
                    {
                        if (isEnum)
                        {
                            CleanText();
                            InsertBeforeDecoder(" <> ");
                            InsertBeforeDecoder(StringifyText.ToString());
                        }
                        else
                            InsertBeforeDecoder(" <> ");

                    }
                    break;

                case ExpressionType.LessThan:
                    InsertBeforeDecoder(" < ");
                    break;

                case ExpressionType.LessThanOrEqual:
                    InsertBeforeDecoder(" <= ");
                    break;

                case ExpressionType.GreaterThan:
                    InsertBeforeDecoder(" > ");
                    break;

                case ExpressionType.GreaterThanOrEqual:
                    InsertBeforeDecoder(" >= ");
                    break;

                default:
                    throw new EnreplacedyException(string.Format("The binary operator '{0}' is not supported", b.NodeType));

            }

            this.Visit(b.Right);
            var exp = (b.Right as BinaryExpression)?.Left;
            var reg = new Regex(@"\b(IsNullOrEmpty|Contains|StartsWith|EndsWith)\b", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            if ((exp == null || exp.Type == typeof(bool) || exp.Type == typeof(bool?)) && (b.Right.Type == typeof(bool) || b.Right.Type == typeof(bool?)) && !reg.Match(b.Right.ToString()).Success)
                validateBinaryExpression(b, null);
            validateBinaryExpression(b, b.Right);

            sb.Append(")");
            return b;
        }

19 Source : CourseExtensionMethods.cs
with MIT License
from AlexChesser

public static int[][] ToMultiDimensionalArray(this string str)
    {
        Regex rxp = new Regex("\\[([0-9,]+?)\\]", RegexOptions.Compiled);
        List<int[]> n = new List<int[]>();
        foreach (Match match in rxp.Matches(str))
        {
            n.Add(match.Groups[1].ToString().ToIntArray());
        }
        return n.ToArray();
    }

19 Source : Plugin.cs
with MIT License
from AlexanderPro

[HandleProcessCorruptedStateExceptions]
        public static string[] GetSupportedExtensions(string fileName)
        {
            try
            {
                var plugin = new Plugin(fileName);
                var pluginLoaded = plugin.LoadModule();
                if (!pluginLoaded) return new string[0];
                var detectString = plugin.ListGetDetectStringExist ? plugin.ListGetDetectString() : string.Empty;
                var regExp = new Regex("EXT=\\\"(\\w+)\\\"", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                var matches = regExp.Matches(detectString);
                var result = matches.Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
                plugin.UnloadModule();
                return result;
            }
            catch
            {
                return new string[0];
            }
        }

19 Source : CSharpArgumentList.cs
with GNU General Public License v3.0
from alexgracianoarj

public override void InitFromString(string declaration)
		{
			if (parameterStringRegex.IsMatch(declaration))
			{
				Clear();

				bool optionalPart = false;
				foreach (Match match in parameterRegex.Matches(declaration))
				{
					Group nameGroup = match.Groups["name"];
					Group typeGroup = match.Groups["type"];
					Group modifierGroup = match.Groups["modifier"];
					Group defvalGroup = match.Groups["defval"];

					if (defvalGroup.Success)
						optionalPart = true;
					else if (optionalPart)
						throw new BadSyntaxException(Strings.ErrorInvalidParameterDeclaration);

					InnerList.Add(new CSharpParameter(nameGroup.Value, typeGroup.Value,
						ParseParameterModifier(modifierGroup.Value), defvalGroup.Value));
				}
			}
			else
			{
				throw new BadSyntaxException(Strings.ErrorInvalidParameterDeclaration);
			}
		}

19 Source : PDFGraphics.cs
with GNU General Public License v3.0
from alexgracianoarj

private static List<string> TokenizeString(string text, string separator)
    {
      Regex regex = new Regex(separator);
      MatchCollection matches = regex.Matches(text);
      List<string> result = new List<string>();
      int pos = 0;
      foreach(Match match in matches)
      {
        result.Add(text.Substring(pos, match.Index - pos));
        result.Add(match.Value);
        pos = match.Index + match.Length;
      }
      result.Add(text.Substring(pos, text.Length - pos));

      return result;
    }

19 Source : JavaArgumentList.cs
with GNU General Public License v3.0
from alexgracianoarj

public override void InitFromString(string declaration)
		{
			if (parameterStringRegex.IsMatch(declaration))
			{
				Clear();
				foreach (Match match in parameterRegex.Matches(declaration))
				{
					Group nameGroup = match.Groups["name"];
					Group typeGroup = match.Groups["type"];

					InnerList.Add(new JavaParameter(nameGroup.Value, typeGroup.Value));
				}
			}
			else
			{
				throw new BadSyntaxException(
					Strings.ErrorInvalidParameterDeclaration);
			}
		}

19 Source : Zone.cs
with Apache License 2.0
from alexreinert

private static List<DnsRecordBase> ParseRecords(StreamReader reader, DomainName origin, int ttl, DnsRecordBase lastRecord)
		{
			List<DnsRecordBase> records = new List<DnsRecordBase>();

			while (!reader.EndOfStream)
			{
				string line = ReadRecordLine(reader);

				if (!String.IsNullOrEmpty(line))
				{
					string[] parts = _lineSplitterRegex.Matches(line).Cast<Match>().Select(x => x.Groups.Cast<Group>().Last(g => g.Success).Value.FromMasterfileLabelRepresentation()).ToArray();

					if (parts[0].Equals("$origin", StringComparison.InvariantCultureIgnoreCase))
					{
						origin = DomainName.ParseFromMasterfile(parts[1]);
					}
					if (parts[0].Equals("$ttl", StringComparison.InvariantCultureIgnoreCase))
					{
						ttl = Int32.Parse(parts[1]);
					}
					if (parts[0].Equals("$include", StringComparison.InvariantCultureIgnoreCase))
					{
						FileStream fileStream = reader.BaseStream as FileStream;

						if (fileStream == null)
							throw new NotSupportedException("Includes only supported when loading files");

						// ReSharper disable once replacedignNullToNotNullAttribute
						string path = Path.Combine(new FileInfo(fileStream.Name).DirectoryName, parts[1]);

						DomainName includeOrigin = (parts.Length > 2) ? DomainName.ParseFromMasterfile(parts[2]) : origin;

						using (StreamReader includeReader = new StreamReader(path))
						{
							records.AddRange(ParseRecords(includeReader, includeOrigin, ttl, lastRecord));
						}
					}
					else
					{
						string domainString;
						RecordType recordType;
						RecordClreplaced recordClreplaced;
						int recordTtl;
						string[] rrData;

						if (Int32.TryParse(parts[0], out recordTtl))
						{
							// no domain, starts with ttl
							if (RecordClreplacedHelper.TryParseShortString(parts[1], out recordClreplaced, false))
							{
								// second is record clreplaced
								domainString = null;
								recordType = RecordTypeHelper.ParseShortString(parts[2]);
								rrData = parts.Skip(3).ToArray();
							}
							else
							{
								// no record clreplaced
								domainString = null;
								recordClreplaced = RecordClreplaced.Invalid;
								recordType = RecordTypeHelper.ParseShortString(parts[1]);
								rrData = parts.Skip(2).ToArray();
							}
						}
						else if (RecordClreplacedHelper.TryParseShortString(parts[0], out recordClreplaced, false))
						{
							// no domain, starts with record clreplaced
							if (Int32.TryParse(parts[1], out recordTtl))
							{
								// second is ttl
								domainString = null;
								recordType = RecordTypeHelper.ParseShortString(parts[2]);
								rrData = parts.Skip(3).ToArray();
							}
							else
							{
								// no ttl
								recordTtl = 0;
								domainString = null;
								recordType = RecordTypeHelper.ParseShortString(parts[1]);
								rrData = parts.Skip(2).ToArray();
							}
						}
						else if (RecordTypeHelper.TryParseShortString(parts[0], out recordType))
						{
							// no domain, start with record type
							recordTtl = 0;
							recordClreplaced = RecordClreplaced.Invalid;
							domainString = null;
							rrData = parts.Skip(2).ToArray();
						}
						else
						{
							domainString = parts[0];

							if (Int32.TryParse(parts[1], out recordTtl))
							{
								// domain, second is ttl
								if (RecordClreplacedHelper.TryParseShortString(parts[2], out recordClreplaced, false))
								{
									// third is record clreplaced
									recordType = RecordTypeHelper.ParseShortString(parts[3]);
									rrData = parts.Skip(4).ToArray();
								}
								else
								{
									// no record clreplaced
									recordClreplaced = RecordClreplaced.Invalid;
									recordType = RecordTypeHelper.ParseShortString(parts[2]);
									rrData = parts.Skip(3).ToArray();
								}
							}
							else if (RecordClreplacedHelper.TryParseShortString(parts[1], out recordClreplaced, false))
							{
								// domain, second is record clreplaced
								if (Int32.TryParse(parts[2], out recordTtl))
								{
									// third is ttl
									recordType = RecordTypeHelper.ParseShortString(parts[3]);
									rrData = parts.Skip(4).ToArray();
								}
								else
								{
									// no ttl
									recordTtl = 0;
									recordType = RecordTypeHelper.ParseShortString(parts[2]);
									rrData = parts.Skip(3).ToArray();
								}
							}
							else
							{
								// domain with record type
								recordType = RecordTypeHelper.ParseShortString(parts[1]);
								recordTtl = 0;
								recordClreplaced = RecordClreplaced.Invalid;
								rrData = parts.Skip(2).ToArray();
							}
						}

						DomainName domain;
						if (String.IsNullOrEmpty(domainString))
						{
							domain = lastRecord.Name;
						}
						else if (domainString == "@")
						{
							domain = origin;
						}
						else if (domainString.EndsWith("."))
						{
							domain = DomainName.ParseFromMasterfile(domainString);
						}
						else
						{
							domain = DomainName.ParseFromMasterfile(domainString) + origin;
						}

						if (recordClreplaced == RecordClreplaced.Invalid)
						{
							recordClreplaced = lastRecord.RecordClreplaced;
						}

						if (recordType == RecordType.Invalid)
						{
							recordType = lastRecord.RecordType;
						}

						if (recordTtl == 0)
						{
							recordTtl = ttl;
						}
						else
						{
							ttl = recordTtl;
						}

						lastRecord = DnsRecordBase.Create(recordType);
						lastRecord.RecordType = recordType;
						lastRecord.Name = domain;
						lastRecord.RecordClreplaced = recordClreplaced;
						lastRecord.TimeToLive = recordTtl;

						if ((rrData.Length > 0) && (rrData[0] == @"\#"))
						{
							lastRecord.ParseUnknownRecordData(rrData);
						}
						else
						{
							lastRecord.ParseRecordData(origin, rrData);
						}

						records.Add(lastRecord);
					}
				}
			}

			return records;
		}

19 Source : Rigctrld.cs
with MIT License
from alexwahl

public string ExecCommand(string command)
        {
            command = command.Replace("\n", String.Empty); // remove line feed from command
            if (command.StartsWith("F"))
            {
                Regex regex = new Regex("^F[ ]*([0-9]{1,})$");
                var matches = regex.Matches(command);
                if (matches.Count > 0)
                {
                    if (matches[0].Groups.Count == 2)
                    {
                        var f_string = matches[0].Groups[1].Value;
                        frequency_set_thread_ = new Thread(() => FrequencyInHzString = f_string);
                        frequency_set_thread_.Start();
                    }
                    return GenerateReturn(HamlibErrorcode.RIG_OK);
                }
                return GenerateReturn(HamlibErrorcode.RIG_EPROTO); ; //wrong or unknown F command
            }
            else if (command.Equals("f"))
            {
                return FrequencyInHzString + "\n"; //return current freq.
            }
            return GenerateReturn(HamlibErrorcode.RIG_ENIMPL); //recieved unsupported command
        }

19 Source : main.cs
with GNU General Public License v3.0
from ALIILAPRO

private void btngetproxy_Click(object sender, EventArgs e)
        {
            this.ProxyList.Clear();
            this.lblproxy.Text = "0";
            try
            {
                HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)WebRequest.Create("https://api.proxyscrape.com?request=getproxies&proxytype=http&timeout=10000&country=all&ssl=all&anonymity=all")).GetResponse();
                string end = new StreamReader(response.GetResponseStream()).ReadToEnd();
                MatchCollection matchCollections = new Regex("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:[0-9]{1,5}").Matches(end);
                try
                {
                    try
                    {
                        foreach (object obj in matchCollections)
                        {
                            Match objectValue = (Match)RuntimeHelpers.GetObjectValue(obj);
                            this.ProxyList.Add(objectValue.Value);
                        }
                    }
                    finally
                    {
                    }
                }
                finally
                {
                }
                int List = this.ProxyList.Count;
                this.lblproxy.Text = string.Concat(new string[]
                {
                    List.ToString()
                });
                List = this.ProxyList.Count;
                this.lblproxy.Text = List.ToString();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

19 Source : frmMain.cs
with GNU General Public License v3.0
from amakvana

private void BtnCheck_Click(object sender, EventArgs e)
        {
            ToggleControls(false);

            // read in current version 
            // get latest version 
            // compare 
            if (!string.IsNullOrWhiteSpace(txtYuzuLocation.Text))
            {
                string yuzuLocation = txtYuzuLocation.Text;

                if (File.Exists(yuzuLocation + "\\version"))
                {
                    // get current version 
                    string currentVersion = "";
                    string latestVersion = "";
                    using (StreamReader sr = File.OpenText(yuzuLocation + "\\version"))
                    {
                        string s = "";
                        while ((s = sr.ReadLine()) != null)
                        {
                            currentVersion = s;
                        }
                    }

                    // get latest version from repo
                    using (var wc = new WebClient())
                    {
                        // fetch latest Yuzu release 
                        string repo = "https://github.com/yuzu-emu/yuzu-mainline/releases/latest";
                        string repoHtml = wc.DownloadString(repo);
                        Regex r = new Regex(@"(?:\/yuzu-emu\/yuzu-mainline\/releases\/download\/[^""]+)");
                        foreach (Match m in r.Matches(repoHtml))
                        {
                            string url = m.Value.Trim();
                            if (url.Contains(".zip") && !url.Contains("debugsymbols"))
                            {
                                latestVersion = url.Split('/')[5].Trim().Remove(0, 11);
                            }
                        }
                    }

                    // compare & tell user 
                    string message = (currentVersion == latestVersion) ? "You have the latest version of Yuzu!" : "Update available, please select Yuzu from the dropdown and click Update";
                    MessageBox.Show(message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Failed to get version, please select Yuzu from the dropdown and click Update", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Please select your Yuzu root folder", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // enable relevant buttons 
            ToggleControls(true);
            if (cboOptions.SelectedIndex == 0 && DependenciesInstalled())
            {
                btnProcess.Enabled = false;
                btnProcess.Text = "Installed";
            }
        }

19 Source : frmMain.cs
with GNU General Public License v3.0
from amakvana

private async Task ProcessYuzu(string yuzuLocation)
        {
            ToggleControls(false);

            // create temp directory for downloads 
            string tempDir = yuzuLocation + "\\TempUpdate";
            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            // get latest yuzu version & download 
            using (var wc = new WebClient())
            {
                // fetch latest Yuzu release 
                string latestYuzu = "https://github.com";
                string repo = "https://github.com/yuzu-emu/yuzu-mainline/releases/latest";
                string repoHtml = wc.DownloadString(repo);
                string version = "";
                Regex r = new Regex(@"(?:\/yuzu-emu\/yuzu-mainline\/releases\/download\/[^""]+)");
                foreach (Match m in r.Matches(repoHtml))
                {
                    string url = m.Value.Trim();
                    if (url.Contains(".zip") && !url.Contains("debugsymbols"))
                    {
                        latestYuzu += url;
                        version = url.Split('/')[5].Trim().Remove(0, 11);
                    }
                }

                // download it 
                wc.DownloadFileCompleted += (s, e) =>
                {
                    // unpack 
                    SetProgressLabelStatus("Unpacking Yuzu ...");
                    ZipFile.ExtractToDirectory(tempDir + "\\yuzu.zip", yuzuLocation);

                    // update version number 
                    using (StreamWriter sw = File.CreateText(yuzuLocation + "\\version"))
                    {
                        sw.Write(version);
                    }

                    // cleanup 
                    DirectoryUtilities.Copy(yuzuLocation + "\\yuzu-windows-msvc", yuzuLocation, true);
                    Directory.Delete(yuzuLocation + "\\yuzu-windows-msvc", true);
                    Directory.Delete(tempDir, true);
                    Directory.EnumerateFiles(yuzuLocation, "*.xz").ToList().ForEach(item => File.Delete(item));
                    SetProgressLabelStatus("Done!");
                    ToggleControls(true);
                    pbarProgress.Value = 0;
                };
                wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
                SetProgressLabelStatus("Downloading Yuzu ...");
                await wc.DownloadFileTaskAsync(new Uri(latestYuzu), tempDir + "\\yuzu.zip");
            }
        }

19 Source : lyricPoster.cs
with GNU General Public License v2.0
from AmanoTooko

internal static Queue<lyricLine> replacedyzeLrc(string path)
        {
            Queue<lyricLine> ret = new Queue<lyricLine>();
            var text = File.ReadAllText(path);
            var reg = new Regex(@"\[(?<time>.*)\](?<lyric>.*)\r\n");
            var c = reg.Matches(text);
            foreach (Match item in c)
            {
                ret.Enqueue(new lyricLine(item.Groups["time"].Value, item.Groups["lyric"].Value));
            }
            return ret;
        }

19 Source : CrossPlatformOperations.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

public static void CopyOldConfigToNewConfig()
        {
            if(currentPlatform.IsWinForms)
            {
                string oldConfigPath = LAUNCHERNAME + ".oldCfg";
                string newConfigPath = LAUNCHERNAME + ".config";
                string oldConfigText = File.ReadAllText(oldConfigPath);
                string newConfigText = File.ReadAllText(newConfigPath);

                Regex settingRegex = new Regex("<add name=\".*\" />");

                MatchCollection oldMatch = settingRegex.Matches(oldConfigText);
                MatchCollection newMatch = settingRegex.Matches(newConfigText);

                for(int i = 0; i < oldMatch.Count; i++)
                    newConfigText = newConfigText.Replace(newMatch[i].Value, oldMatch[i].Value);

                File.WriteAllText(newConfigPath, newConfigText);

            }
            else if(currentPlatform.IsGtk)
            {
                string homePath = Environment.GetEnvironmentVariable("HOME");
                string launcherConfigPath = homePath + "/.config/AM2RLauncher/";
                string launcherConfigFilePath = launcherConfigPath + "config.xml";
                XML.LauncherConfigXML launcherConfig = new XML.LauncherConfigXML();

                //for some reason deserializing and saving back again works, not exactly sure why, but I'll take it
                launcherConfig = XML.Serializer.Deserialize<XML.LauncherConfigXML>(File.ReadAllText(launcherConfigFilePath));
                File.WriteAllText(launcherConfigFilePath, XML.Serializer.Serialize<XML.LauncherConfigXML>(launcherConfig));
            }
        }

19 Source : AnkhIssueService.cs
with Apache License 2.0
from AmpScm

private IEnumerable<TextMarker> PerformRepositoryRegex(Regex re, string text)
        {
            if (re == null)
                yield break;

            foreach (Match m in re.Matches(text))
            {
                if (!m.Success)
                    continue;

                // try to find an "ID" group
                Group grp = m.Groups[REGEX_GROUPNAME_ID];
                if (grp != null && grp.Success)
                {
                    foreach (Capture c in grp.Captures)
                        yield return new TextMarker(c.Index, c.Length, c.Value);
                }
                else
                {
                    foreach (Group g in m.Groups)
                    {
                        foreach (Capture c in g.Captures)
                            yield return new TextMarker(c.Index, c.Length, c.Value);
                    }
                }
            }
        }

19 Source : SolutionSettings.Commit.cs
with Apache License 2.0
from AmpScm

private IEnumerable<TextMarker> PerformRevisionScan(SettingsCache cache, string logmessage)
        {
            if (_revRe == null)
                _revRe = new Regex(@"\d+", RegexOptions.Multiline | RegexOptions.CultureInvariant);

            foreach (Match m in cache.RevisionRe.Matches(logmessage))
            {
                if (!m.Success)
                    continue;

                foreach (Capture c in m.Captures)
                {
                    string text = logmessage.Substring(c.Index, c.Length);

                    foreach (Match sm in _revRe.Matches(c.Value))
                    {
                        if (!sm.Success)
                            continue;

                        foreach (Capture sc in sm.Captures)
                        {
                            yield return new TextMarker(c.Index + sc.Index, sc.Length, sc.Value);
                        }
                    }
                }
            }
        }

19 Source : Host.cs
with MIT License
from ancientproject

public static string Evolve(string code) // todo REWORK IT
        {
            var result = code;
            var parsed = new TransformerSyntax().ManyEvolver.Parse(code);
            foreach (var token in parsed.Pipe(x => Trace($"evolving :: {x}")))
            {
                switch (token)
                {
                    case EmptyEvolve _:
                        break;
                    case LocalsInitEvolver local:
                        var dd = result.Split('\n').ToList();
                        dd.Insert(token.InputPosition.Line-1, $"{string.Join(" ", local.Result)}\n");
                        result = string.Join("\n", dd);
                        break;
                    case DefineLabels labels:
                        var reg = new Regex(@"\!\[~(?<alias>\w+)\]");

                        var usedAliases = reg.Matches(code).Select(x => x.Groups["alias"].Value).ToArray();
                        var compiledAliases = labels.Labels.Select(x => x.Name).ToList();

                        var failedFind = usedAliases.Where(x => !compiledAliases.Contains(x)).ToArray();

                        if (failedFind.Any())
                        {
                            var msg = $"[{string.Join(",", failedFind)}] symbols not compiled.";
                            Error(Warning.PrecompiledSymbolNotFound, msg);
                            throw new AncientEvolveException(msg);
                        }

                        result = labels.Labels.Aggregate(result, (current, aliase) => 
                                current.Replace($"![~{aliase.Name}]", $"0x{aliase.Hex}"));
                        break;
                    case ErrorEvolveToken error:
                        Error(error, code);
                        throw new AncientEvolveException(error.ErrorResult.ToString());
                }
            }
            return result;
        }

19 Source : Util.cs
with MIT License
from AndyCW

public static string GetVisibleSerial(string name)
        {
            string result = "";                                  //NON-NLS
            Regex rgx;
            //if (BuildConfig.DEBUG) {
            // Everything after last whitespace and possible '#'
            rgx = new Regex(@"([^\s#]*)$"); // NON-NLS
            /*
            } else {
                // Digits at the end of the string, must be 8-14 digits.
                // The first digit can be replaced with P in prototype devices.
                pattern = Pattern.compile("(P?[0-9]{7,14}$)"); //NON-NLS
            }
            */

            MatchCollection matches = rgx.Matches(name);
            if (matches.Count > 0)
            {
                result = matches[0].Value;                        // Returns the input subsequence matched by the previous match.
            }
            return result;
        }

19 Source : Anki.cs
with MIT License
from AnkiTools

private void AddFields(JObject models, List<double> mids)
        {
            var regex = new Regex("{{hint:(.*?)}}|{{type:(.*?)}}|{{(.*?)}}");

            foreach (var mid in mids)
            {
                var qfmt = models["" + mid]["tmpls"].First["qfmt"].ToString().Replace("\"", "");
                var afmt = models["" + mid]["tmpls"].First["afmt"].ToString();
                var css = models["" + mid]["css"].ToString();

                afmt = afmt.Replace("{{FrontSide}}", qfmt);

                var matches = regex.Matches(afmt);
                FieldList fields = new FieldList();

                foreach (Match match in matches)
                {
                    if (match.Value.Contains("type:") || match.Value.Contains("hint:"))
                        continue;

                    var value = match.Value;
                    var field = new Field(value.Replace("{{", "").Replace("}}", ""));

                    fields.Add(field);
                }

                _infoPerMid.Add("" + mid, new Info(afmt.Replace("\n", "\\n"), css.Replace("\n", "\\n"), fields));
            }
        }

See More Examples