char.IsLetterOrDigit(char)

Here are the examples of the csharp api char.IsLetterOrDigit(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

542 Examples 7

19 Source : IndexAndSearchHandler.cs
with MIT License
from 0ffffffffh

private string NormalizeTerm(string s)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var c in s)
            {
                if (char.IsLetterOrDigit(c) || c == ' ')
                    sb.Append(char.ToLower(c));
                else if (char.IsSeparator(c))
                    sb.Append(' ');
            }

            s = sb.ToString();
            sb.Clear();
            sb = null;

            return s;
        }

19 Source : StringHelper.cs
with MIT License
from 0x1000000

public static string DeSnake(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }

            char[]? result = null;
            int nextResultIndex = 0;

            bool afterSymbol = true;

            for (int i = 0; i < input.Length; i++)
            {
                var ch = input[i];

                if (!char.IsLetterOrDigit(ch))
                {
                    afterSymbol = true;
                    EnsureResult(i);
                }
                else
                {
                    if (afterSymbol && char.IsLower(ch))
                    {
                        OutResult(i, char.ToUpper(ch), true);
                    }
                    else
                    {
                        OutResult(i, ch, false);
                    }
                    afterSymbol = false;
                }

                if (result == null)
                {
                    nextResultIndex = i;
                }
            }

            return result == null ? input : new string(result, 0, nextResultIndex);

            void EnsureResult(int index)
            {
                if (result == null)
                {
                    result = new char[input.Length + 1];
                    input.CopyTo(0, result, 0, input.Length);
                    nextResultIndex = index;
                }
            }

            void OutResult(int index, char ch, bool changed)
            {
                var isFirstDigit = nextResultIndex == 0 && char.IsDigit(ch);
                if (result == null)
                {
                    if (!changed && !isFirstDigit)
                    {
                        return;
                    }

                    EnsureResult(index);
                }

                if (isFirstDigit)
                {
                    result![nextResultIndex++] = 'D';
                }

                result![nextResultIndex++] = ch;
            }
        }

19 Source : XmlHighlightingDefinition.cs
with MIT License
from Abdesol

public object VisitKeywords(XshdKeywords keywords)
			{
				if (keywords.Words.Count == 0)
					return Error(keywords, "Keyword group must not be empty.");
				foreach (string keyword in keywords.Words) {
					if (string.IsNullOrEmpty(keyword))
						throw Error(keywords, "Cannot use empty string as keyword");
				}
				StringBuilder keyWordRegex = new StringBuilder();
				// We can use "\b" only where the keyword starts/ends with a letter or digit, otherwise we don't
				// highlight correctly. (example: ILAsm-Mode.xshd with ".maxstack" keyword)
				if (keywords.Words.All(IsSimpleWord)) {
					keyWordRegex.Append(@"\b(?>");
					// (?> = atomic group
					// atomic groups increase matching performance, but we
					// must ensure that the keywords are sorted correctly.
					// "\b(?>in|int)\b" does not match "int" because the atomic group captures "in".
					// To solve this, we are sorting the keywords by descending length.
					int i = 0;
					foreach (string keyword in keywords.Words.OrderByDescending(w => w.Length)) {
						if (i++ > 0)
							keyWordRegex.Append('|');
						keyWordRegex.Append(Regex.Escape(keyword));
					}
					keyWordRegex.Append(@")\b");
				} else {
					keyWordRegex.Append('(');
					int i = 0;
					foreach (string keyword in keywords.Words) {
						if (i++ > 0)
							keyWordRegex.Append('|');
						if (char.IsLetterOrDigit(keyword[0]))
							keyWordRegex.Append(@"\b");
						keyWordRegex.Append(Regex.Escape(keyword));
						if (char.IsLetterOrDigit(keyword[keyword.Length - 1]))
							keyWordRegex.Append(@"\b");
					}
					keyWordRegex.Append(')');
				}
				return new HighlightingRule {
					Color = GetColor(keywords, keywords.ColorReference),
					Regex = CreateRegex(keywords, keyWordRegex.ToString(), XshdRegexType.Default)
				};
			}

19 Source : IndentationReformatter.cs
with MIT License
from Abdesol

public void Step(IDoreplacedentAccessor doc, IndentationSettings set)
		{
			string line = doc.Text;
			if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
			line = line.TrimStart();

			StringBuilder indent = new StringBuilder();
			if (line.Length == 0) {
				// Special treatment for empty lines:
				if (blockComment || (inString && verbatim))
					return;
				indent.Append(block.InnerIndent);
				indent.Append(Repeat(set.IndentString, block.OneLineBlock));
				if (block.Continuation)
					indent.Append(set.IndentString);
				if (doc.Text != indent.ToString())
					doc.Text = indent.ToString();
				return;
			}

			if (TrimEnd(doc))
				line = doc.Text.TrimStart();

			Block oldBlock = block;
			bool startInComment = blockComment;
			bool startInString = (inString && verbatim);

			#region Parse char by char
			lineComment = false;
			inChar = false;
			escape = false;
			if (!verbatim) inString = false;

			lastRealChar = '\n';

			char lastchar = ' ';
			char c = ' ';
			char nextchar = line[0];
			for (int i = 0; i < line.Length; i++) {
				if (lineComment) break; // cancel parsing current line

				lastchar = c;
				c = nextchar;
				if (i + 1 < line.Length)
					nextchar = line[i + 1];
				else
					nextchar = '\n';

				if (escape) {
					escape = false;
					continue;
				}

				#region Check for comment/string chars
				switch (c) {
					case '/':
						if (blockComment && lastchar == '*')
							blockComment = false;
						if (!inString && !inChar) {
							if (!blockComment && nextchar == '/')
								lineComment = true;
							if (!lineComment && nextchar == '*')
								blockComment = true;
						}
						break;
					case '#':
						if (!(inChar || blockComment || inString))
							lineComment = true;
						break;
					case '"':
						if (!(inChar || lineComment || blockComment)) {
							inString = !inString;
							if (!inString && verbatim) {
								if (nextchar == '"') {
									escape = true; // skip escaped quote
									inString = true;
								} else {
									verbatim = false;
								}
							} else if (inString && lastchar == '@') {
								verbatim = true;
							}
						}
						break;
					case '\'':
						if (!(inString || lineComment || blockComment)) {
							inChar = !inChar;
						}
						break;
					case '\\':
						if ((inString && !verbatim) || inChar)
							escape = true; // skip next character
						break;
				}
				#endregion

				if (lineComment || blockComment || inString || inChar) {
					if (wordBuilder.Length > 0)
						block.LastWord = wordBuilder.ToString();
					wordBuilder.Length = 0;
					continue;
				}

				if (!Char.IsWhiteSpace(c) && c != '[' && c != '/') {
					if (block.Bracket == '{')
						block.Continuation = true;
				}

				if (Char.IsLetterOrDigit(c)) {
					wordBuilder.Append(c);
				} else {
					if (wordBuilder.Length > 0)
						block.LastWord = wordBuilder.ToString();
					wordBuilder.Length = 0;
				}

				#region Push/Pop the blocks
				switch (c) {
					case '{':
						block.ResetOneLineBlock();
						blocks.Push(block);
						block.StartLine = doc.LineNumber;
						if (block.LastWord == "switch") {
							block.Indent(set.IndentString + set.IndentString);
							/* oldBlock refers to the previous line, not the previous block
							 * The block we want is not available anymore because it was never pushed.
							 * } else if (oldBlock.OneLineBlock) {
							// Inside a one-line-block is another statement
							// with a full block: indent the inner full block
							// by one additional level
							block.Indent(set, set.IndentString + set.IndentString);
							block.OuterIndent += set.IndentString;
							// Indent current line if it starts with the '{' character
							if (i == 0) {
								oldBlock.InnerIndent += set.IndentString;
							}*/
						} else {
							block.Indent(set);
						}
						block.Bracket = '{';
						break;
					case '}':
						while (block.Bracket != '{') {
							if (blocks.Count == 0) break;
							block = blocks.Pop();
						}
						if (blocks.Count == 0) break;
						block = blocks.Pop();
						block.Continuation = false;
						block.ResetOneLineBlock();
						break;
					case '(':
					case '[':
						blocks.Push(block);
						if (block.StartLine == doc.LineNumber)
							block.InnerIndent = block.OuterIndent;
						else
							block.StartLine = doc.LineNumber;
						block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
									 (oldBlock.Continuation ? set.IndentString : "") +
									 (i == line.Length - 1 ? set.IndentString : new String(' ', i + 1)));
						block.Bracket = c;
						break;
					case ')':
						if (blocks.Count == 0) break;
						if (block.Bracket == '(') {
							block = blocks.Pop();
							if (IsSingleStatementKeyword(block.LastWord))
								block.Continuation = false;
						}
						break;
					case ']':
						if (blocks.Count == 0) break;
						if (block.Bracket == '[')
							block = blocks.Pop();
						break;
					case ';':
					case ',':
						block.Continuation = false;
						block.ResetOneLineBlock();
						break;
					case ':':
						if (block.LastWord == "case"
							|| line.StartsWith("case ", StringComparison.Ordinal)
							|| line.StartsWith(block.LastWord + ":", StringComparison.Ordinal)) {
							block.Continuation = false;
							block.ResetOneLineBlock();
						}
						break;
				}

				if (!Char.IsWhiteSpace(c)) {
					// register this char as last char
					lastRealChar = c;
				}
				#endregion
			}
			#endregion

			if (wordBuilder.Length > 0)
				block.LastWord = wordBuilder.ToString();
			wordBuilder.Length = 0;

			if (startInString) return;
			if (startInComment && line[0] != '*') return;
			if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
				return;

			if (line[0] == '}') {
				indent.Append(oldBlock.OuterIndent);
				oldBlock.ResetOneLineBlock();
				oldBlock.Continuation = false;
			} else {
				indent.Append(oldBlock.InnerIndent);
			}

			if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') {
				indent.Remove(indent.Length - 1, 1);
			} else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') {
				indent.Remove(indent.Length - 1, 1);
			}

			if (line[0] == ':') {
				oldBlock.Continuation = true;
			} else if (lastRealChar == ':' && indent.Length >= set.IndentString.Length) {
				if (block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(block.LastWord + ":", StringComparison.Ordinal))
					indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
			} else if (lastRealChar == ')') {
				if (IsSingleStatementKeyword(block.LastWord)) {
					block.OneLineBlock++;
				}
			} else if (lastRealChar == 'e' && block.LastWord == "else") {
				block.OneLineBlock = Math.Max(1, block.PreviousOneLineBlock);
				block.Continuation = false;
				oldBlock.OneLineBlock = block.OneLineBlock - 1;
			}

			if (doc.IsReadOnly) {
				// We can't change the current line, but we should accept the existing
				// indentation if possible (=if the current statement is not a multiline
				// statement).
				if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
					oldBlock.StartLine == block.StartLine &&
					block.StartLine < doc.LineNumber && lastRealChar != ':') {
					// use indent StringBuilder to get the indentation of the current line
					indent.Length = 0;
					line = doc.Text; // get untrimmed line
					for (int i = 0; i < line.Length; ++i) {
						if (!Char.IsWhiteSpace(line[i]))
							break;
						indent.Append(line[i]);
					}
					// /* */ multiline comments have an extra space - do not count it
					// for the block's indentation.
					if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') {
						indent.Length -= 1;
					}
					block.InnerIndent = indent.ToString();
				}
				return;
			}

			if (line[0] != '{') {
				if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
					indent.Append(set.IndentString);
				indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
			}

			// this is only for blockcomment lines starting with *,
			// all others keep their old indentation
			if (startInComment)
				indent.Append(' ');

			if (indent.Length != (doc.Text.Length - line.Length) ||
				!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
				Char.IsWhiteSpace(doc.Text[indent.Length])) {
				doc.Text = indent.ToString() + line;
			}
		}

19 Source : XmlHighlightingDefinition.cs
with MIT License
from Abdesol

static bool IsSimpleWord(string word)
			{
				return char.IsLetterOrDigit(word[0]) && char.IsLetterOrDigit(word, word.Length - 1);
			}

19 Source : ParentLexer.cs
with MIT License
from Actipro

protected virtual int ParseIdentifier(ITextBufferReader reader, char ch) {
			// Get the entire word
			int startOffset = reader.Offset - 1;
			while (!reader.IsAtEnd) {
				char ch2 = reader.Read();
				if ((!char.IsLetterOrDigit(ch2)) && (ch2 != '_')) {
					reader.ReadReverse();
					break;
				}
			}

			// This language only has one keyword named "date"
			if (reader.GetSubstring(startOffset, reader.Offset - startOffset) == "date")
				return ParentTokenId.DateKeyword;

			// Word is an identifier
			return ParentTokenId.Identifier;
		}

19 Source : SimpleLexer.cs
with MIT License
from Actipro

protected virtual int ParseIdentifier(ITextBufferReader reader, char ch) {
			// Get the entire word
			int startOffset = reader.Offset - 1;
			while (!reader.IsAtEnd) {
				char ch2 = reader.Read();
				// NOTE: This could be improved by supporting \u escape sequences
				if ((!char.IsLetterOrDigit(ch2)) && (ch2 != '_')) {
					reader.ReadReverse();
					break;
				}
			}

			// Determine if the word is a keyword
			if (Char.IsLetter(ch)) {
				int value;
				String subString = reader.GetSubstring(startOffset, reader.Offset - startOffset);
				if (!caseSensitive)
					subString = subString.ToLowerInvariant();

				return keywords.TryGetValue(subString, out value) ? value : SimpleTokenId.Identifier;
			}
			else
				return SimpleTokenId.Identifier;
		}

19 Source : Utils.cs
with MIT License
from agens-no

static bool DontNeedQuotes(string src)
        {
            // using a regex instead of explicit matching slows down common cases by 40%
            if (src.Length == 0)
                return false;

            bool hreplacedlash = false;
            for (int i = 0; i < src.Length; ++i)
            {
                char c = src[i];
                if (Char.IsLetterOrDigit(c) || c == '.' || c == '*' || c == '_')
                    continue;
                if (c == '/')
                {
                    hreplacedlash = true;
                    continue;
                }
                return false;
            }
            if (hreplacedlash)
            {
                if (src.Contains("//") || src.Contains("/*") || src.Contains("*/"))
                    return false;
            }
            return true;
        }

19 Source : Wallet.cs
with Apache License 2.0
from ajuna-network

public bool IsValidWalletName(string walletName)
        {
            return walletName.Length > 4 && walletName.Length < 21 &&
                   walletName.All(c => char.IsLetterOrDigit(c) || c.Equals('_'));
        }

19 Source : JsonTextReader.cs
with MIT License
from akaskela

private bool ValidIdentifierChar(char value)
        {
            return (char.IsLetterOrDigit(value) || value == '_' || value == '$');
        }

19 Source : JsonTextReader.cs
with MIT License
from akaskela

private void ParseConstructor()
        {
            if (MatchValueWithTrailingSeparator("new"))
            {
                EatWhitespace(false);

                int initialPosition = _charPos;
                int endPosition;

                while (true)
                {
                    char currentChar = _chars[_charPos];
                    if (currentChar == '\0')
                    {
                        if (_charsUsed == _charPos)
                        {
                            if (ReadData(true) == 0)
                            {
                                throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
                            }
                        }
                        else
                        {
                            endPosition = _charPos;
                            _charPos++;
                            break;
                        }
                    }
                    else if (char.IsLetterOrDigit(currentChar))
                    {
                        _charPos++;
                    }
                    else if (currentChar == StringUtils.CarriageReturn)
                    {
                        endPosition = _charPos;
                        ProcessCarriageReturn(true);
                        break;
                    }
                    else if (currentChar == StringUtils.LineFeed)
                    {
                        endPosition = _charPos;
                        ProcessLineFeed();
                        break;
                    }
                    else if (char.IsWhiteSpace(currentChar))
                    {
                        endPosition = _charPos;
                        _charPos++;
                        break;
                    }
                    else if (currentChar == '(')
                    {
                        endPosition = _charPos;
                        break;
                    }
                    else
                    {
                        throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
                    }
                }

                _stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
                string constructorName = _stringReference.ToString();

                EatWhitespace(false);

                if (_chars[_charPos] != '(')
                {
                    throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
                }

                _charPos++;

                ClearRecentString();

                SetToken(JsonToken.StartConstructor, constructorName);
            }
            else
            {
                throw JsonReaderException.Create(this, "Unexpected content while parsing JSON.");
            }
        }

19 Source : HtmlCssParser.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private static bool ParseWord(string word, string styleValue, ref int nextIndex)
        {
            ParseWhiteSpace(styleValue, ref nextIndex);

            for (int i = 0; i < word.Length; i++)
            {
                if (!(nextIndex + i < styleValue.Length && word[i] == styleValue[nextIndex + i]))
                {
                    return false;
                }
            }

            if (nextIndex + word.Length < styleValue.Length && Char.IsLetterOrDigit(styleValue[nextIndex + word.Length]))
            {
                return false;
            }

            nextIndex += word.Length;
            return true;
        }

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

private void ReadIdentifier()
        {
            while (char.IsLetterOrDigit(Peek()))
            {
                Advance();
            }

            var text = _source.Substring(_start, _current - _start);

            // "not" can only be used with "like"
            if (text.ToLower() == "not")
            {
                while (char.IsWhiteSpace(Peek()))
                {
                    Advance();
                }

                var start = _current;

                while (char.IsLetter(Peek()))
                {
                    Advance();
                }

                text = _source.Substring(start, _current - start).ToLower();
                if (text == "like")
                {
                    AddToken(TokenType.NotLike);
                }
                else
                {
                    throw new QueryEngineException($"Unexpected character at position '{start + 1}': \"not\" keyword may only be used with \"like\" keyword.");
                }
            }
            else
            {
                var type = _keywords.ContainsKey(text.ToLower()) ? _keywords[text.ToLower()] : (TokenType?)null;
                AddToken(type is null ? TokenType.Identifier : type.Value);
            }
        }

19 Source : AppUserService.cs
with MIT License
from alexyakunin

private async Task<string> NormalizeName(AppDbContext dbContext, string name, long userId, CancellationToken cancellationToken = default)
        {
            // Normalizing name
            var sb = StringBuilderEx.Acquire();
            foreach (var c in name) {
                if (char.IsLetterOrDigit(c) || c == '_' || c == '-')
                    sb.Append(c);
                else if (sb.Length == 0 || char.IsLetterOrDigit(sb[^1]))
                    sb.Append('_');
            }
            name = sb.ToStringAndRelease();
            if (name.Length < 4 || !char.IsLetter(name[0]))
                name = "user-" + name;

            // Finding the number @ the tail
            var numberStartIndex = name.Length;
            for (; numberStartIndex >= 1; numberStartIndex--) {
                if (!char.IsNumber(name[numberStartIndex - 1]))
                    break;
            }

            // Iterating through these tail numbers to get the unique user name
            var namePrefix = name.Substring(0, numberStartIndex);
            var nameSuffix = name.Substring(numberStartIndex);
            var nextNumber = long.TryParse(nameSuffix, out var number) ? number + 1 : 1;
            while (true) {
                var isNameUsed = await dbContext.Users.AsQueryable()
                    .AnyAsync(u => u.Name == name && u.Id != userId, cancellationToken);
                if (!isNameUsed)
                    break;
                name = namePrefix + nextNumber++;
            }
            return name;
        }

19 Source : UserNameService.cs
with MIT License
from alexyakunin

public string ParseName(string text, int startIndex = 0)
        {
            string name;
            for (var i = startIndex; i < text.Length; i++) {
                var c = text[i];
                if (i == startIndex) {
                    if (char.IsLetter(c))
                        continue;
                    return "";
                }
                if (char.IsLetterOrDigit(c) || c == '_' || c == '-')
                    continue;
                name = text.Substring(startIndex, i - startIndex);
                return ValidateName(name) == null ? name : "";
            }
            name = text.Substring(startIndex);
            return ValidateName(name) == null ? name : "";
        }

19 Source : Lexer.cs
with MIT License
from alirezanet

public SyntaxToken NextToken()
      {
         if (_position >= _text.Length) return new SyntaxToken(SyntaxKind.End, _position, "\0");

         var peek = Peek(1);
         switch (Current)
         {
            case '(':
               return new SyntaxToken(SyntaxKind.OpenParenthesisToken, _position++, "(");
            case ')':
               return new SyntaxToken(SyntaxKind.CloseParenthesis, _position++, ")");
            case ',':
               return new SyntaxToken(SyntaxKind.And, _position++, ",");
            case '|':
               return new SyntaxToken(SyntaxKind.Or, _position++, "|");
            case '^':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.StartsWith, _position++, "^");
            }
            case '$':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.EndsWith, _position++, "$");
            }
            case '!' when peek == '^':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotStartsWith, _position += 2, "!^");
            }
            case '!' when peek == '$':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotEndsWith, _position += 2, "!$");
            }
            case '=' when peek == '*':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.Like, _position += 2, "=*");
            }
            case '=':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.Equal, _position ++ , "=");
            }
            case '!' when peek == '=':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotEqual, _position += 2, "!=");
            }
            case '!' when peek == '*':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotLike, _position += 2, "!*");
            }
            case '/' when peek == 'i':
               return new SyntaxToken(SyntaxKind.CaseInsensitive, _position += 2, "/i");
            case '<':
            {
               _waitingForValue = true;
               return peek == '=' ? new SyntaxToken(SyntaxKind.LessOrEqualThan, _position += 2, "<=") :
                  new SyntaxToken(SyntaxKind.LessThan, _position++, "<");
            }
            case '>':
            {
               _waitingForValue = true;
               return peek == '=' ? new SyntaxToken(SyntaxKind.GreaterOrEqualThan, _position += 2, ">=") : 
                  new SyntaxToken(SyntaxKind.GreaterThan, _position++, ">");
            }
         }

         if (Current == '[')
         {
            Next();
            var start = _position; 
            while (char.IsDigit(Current))  
               Next();
      
            var length = _position - start;
            var text = _text.Substring(start, length);

            if (Current == ']')
            {
               _position++;
               return new SyntaxToken(SyntaxKind.FieldIndexToken, start, text);
            }
            
            _diagnostics.Add($"bad character input: '{peek.ToString()}' at {_position++.ToString()}. expected ']' ");
            return new SyntaxToken(SyntaxKind.BadToken, _position, Current.ToString());

         }

         if (char.IsLetter(Current) && !_waitingForValue)
         {
            var start = _position;

            while (char.IsLetterOrDigit(Current) || Current is '_')  
               Next();

            var length = _position - start;
            var text = _text.Substring(start, length);
            
            return new SyntaxToken(SyntaxKind.FieldToken, start, text);
         }
         

         if (char.IsWhiteSpace(Current))
         {
            var start = _position;

            // skipper
            while (char.IsWhiteSpace(Current))
               Next();

            var length = _position - start;
            var text = _text.Substring(start, length);

            return new SyntaxToken(SyntaxKind.WhiteSpace, start, text);
         }

         if (_waitingForValue)
         {
            var start = _position;

            var exitCharacters = new[] {'(', ')', ',', '|'};
            var lastChar = '\0';
            while ((!exitCharacters.Contains(Current) || exitCharacters.Contains(Current) && lastChar == '\\') &&
                   _position < _text.Length &&
                   (!(Current == '/' && Peek(1) == 'i') || (Current == '/' && Peek(1) == 'i') && lastChar == '\\')) // exit on case-insensitive operator
            {
               lastChar = Current;
               Next();
            }

            var text = new StringBuilder();
            for (var i = start; i < _position; i++)
            {
               var current = _text[i];

               if (current != '\\') // ignore escape character
                  text.Append(current);
               else if (current == '\\' && i > 0) // escape escape character
                  if (_text[i - 1] == '\\')
                     text.Append(current);
            }

            _waitingForValue = false;
            return new SyntaxToken(SyntaxKind.ValueToken, start, text.ToString());
         }

         _diagnostics.Add($"bad character input: '{Current.ToString()}' at {_position.ToString()}");
         return new SyntaxToken(SyntaxKind.BadToken, _position++, string.Empty);
      }

19 Source : StringExtensions.cs
with MIT License
from allisterb

public static bool IsAlphaNumeric(this string value)
        {
            return value.All(c => Char.IsLetterOrDigit(c));
        }

19 Source : StringExtensions.cs
with MIT License
from allisterb

public static string ToAlphaNumeric(this string s)
        {
            char[] chars = s.Where(c => Char.IsLetterOrDigit(c)).ToArray();
            return new String(chars);
        }

19 Source : CharExtension.cs
with MIT License
from AlphaYu

public static bool IsLetterOrDigit(this char c)
        {
            return char.IsLetterOrDigit(c);
        }

19 Source : Lexer.cs
with MIT License
from Alprog

public IEnumerator<Token> Tokenize(string line)
        {
            var token = new Token(TokenType.Invalid, 0, line.Length);
            int i = 0;
            while (i < line.Length)
            {
                var c = line[i];
                if (Char.IsWhiteSpace(c))
                {
                    // WhiteSpace
                    i++;
                    continue;
                }
                else if (Char.IsLetter(c) || c.Equals('_'))
                {
                    // Identifier or Keyword
                    int si = i; i++;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (Char.IsLetterOrDigit(c) || c.Equals('_'))
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    var tokenText = line.Substring(si, i - si);
                    if (tokenText.ToLower() == "true")
                    {
                        token = ValueToken(si, i - si, true);
                    }
                    else if (tokenText.ToLower() == "false")
                    {
                        token = ValueToken(si, i - si, false);
                    }
                    else if (tokenText.ToLower() == "null")
                    {
                        token = ValueToken(si, i - si, null);
                    }
                    else
                    {
                        if (i < line.Length && line[i].Equals('…'))
                        {
                            token = new Token(TokenType.Autocomplete, si, i - si, tokenText);
                            i++;
                        }
                        else
                        {
                            token = new Token(TokenType.Identifier, si, i - si, tokenText);
                        }
                    }
                }
                else if (c.Equals('\"'))
                {
                    // String
                    int si = i; i++;
                    bool ended = false;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (!c.Equals('\"'))
                        {
                            i++;
                        }
                        else
                        {
                            ended = true;
                            i++;
                            break;
                        }
                    }
                    if (ended)
                    {
                        var text = line.Substring(si + 1, i - si - 2);
                        token = ValueToken(si, i - si, text);
                    }
                    else
                    {
                        token = new Token(TokenType.Invalid, si, i - si);
                    }
                }
                else if (Char.IsDigit(c) || c.Equals('-'))
                {
                    // Minus or digit
                    if (c.Equals('-'))
                    {
                        if (token.Type == TokenType.Value ||
                            token.Type == TokenType.Identifier ||
                            token.Type == TokenType.ClosedBracket)
                        {
                            // force minus operator
                            i++;
                            token = new Token(TokenType.Operator, i, 1, Operator.Get("-"));
                            yield return token;
                            continue;
                        }
                    }

                    int si = i; i++;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (Char.IsDigit(c) || c.Equals('.'))
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    var tokenText = line.Substring(si, i - si);
                    if (tokenText == "-")
                    {
                        token = new Token(TokenType.Operator, si, i - si, Operator.Get(tokenText));
                        i++;
                    }
                    else
                    {
                        float number;
                        if (Single.TryParse(tokenText, NumberStyles.Any, CultureInfo.InvariantCulture, out number))
                        {
                            token = ValueToken(si, i - si, number);
                        }
                        else
                        {
                            token = new Token(TokenType.Invalid, si, i - si);
                        }
                    }
                }
                else if (operators.Contains(c.ToString()))
                {
                    // Operator
                    int si = i; i++;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (operators.Contains(c.ToString()))
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    var tokenText = line.Substring(si, i - si);
                    if (tokenText == "=")
                    {
                        token = new Token(TokenType.replacedignmentOperator, si, i - si);
                    }
                    else
                    {
                        token = new Token(TokenType.Operator, si, i - si, Operator.Get(tokenText));
                    }
                }
                else if (c.Equals('.'))
                {
                    token = new Token(TokenType.Dot, i, 1);
                    i++;
                }
                else if (c.Equals('('))
                {
                    token = new Token(TokenType.OpenBracket, i, 1);
                    i++;
                }
                else if (c.Equals(')'))
                {
                    token = new Token(TokenType.ClosedBracket, i, 1);
                    i++;
                }
                else if (c.Equals(','))
                {
                    token = new Token(TokenType.Comma, i, 1);
                    i++;
                }
                else if (c.Equals('…'))
                {
                    token = new Token(TokenType.Autocomplete, i, 1, String.Empty);
                    i++;
                }
                else
                {
                    token = new Token(TokenType.Invalid, i, 1);
                    i++;
                }

                yield return token;
            }

            yield return new Token(TokenType.EndOfLine, i, 0);
        }

19 Source : CsharpFromJsonExampleFactory.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private static IEnumerable<char> SafeCsNameCharacters(string name, bool upperCaseFirstCharacter)
        {
            if (string.IsNullOrEmpty(name))
            {
                yield break;
            }

            var first = true;
            foreach (var c in name)
            {
                if (first)
                {
                    if (c == '_' || char.IsLetter(c))
                    {
                        yield return upperCaseFirstCharacter ? char.ToUpper(c) : c;
                    }
                    else
                    {
                        yield return '_';
                    }

                    first = false;
                }
                else
                {
                    yield return c == '_' || char.IsLetterOrDigit(c) ? c : '_';
                }
            }
        }

19 Source : StringExtension.cs
with MIT License
from AlturosDestinations

public static string ReplaceSpecialCharacters(this string str, char replacementChar = '_')
        {
            var sb = new StringBuilder();

            foreach (var c in str)
            {
                sb.Append(char.IsLetterOrDigit(c) ? c : replacementChar);
            }

            return sb.ToString();
        }

19 Source : CodeEditorView.xaml.cs
with MIT License
from Aminator

private bool IsValidCSharpIdentifierCharacter(char value)
        {
            return value == '_' || char.IsLetterOrDigit(value);
        }

19 Source : QueryLexicalAnalizer.cs
with MIT License
from ansel86castro

private String ReadWord(int simbol)
        {
            StringBuilder sb = new StringBuilder();
            int c = Peek();
            while (c > 0)
            {
                c = Peek();
                if (c == -1)
                {
                    break;
                }

                if (IsWhiteSpace(c) || IsSymbol(c) != TokenType.UNKNOW || c == '\'')
                {
                    break;
                }
                else if (!Char.IsLetterOrDigit((char)c) && c != '_')
                {
                    throw new TokenMismatchException(String.Format("Expecting ID '{0}' at COL {1} ROW {2}", sb.ToString(), Col, Row));
                }

                sb.Append((char)c);
                Read();
            }
            return sb.ToString();
        }

19 Source : TemplateProcessor.cs
with MIT License
from ansel86castro

static string ReadSymbol(string template, ref int i)
        {
            if (IsSymbol(template, i, out bool matchCloseBracket))
            {
                StringBuilder sb = new StringBuilder();
                i += 2;

                if (matchCloseBracket)
                {
                    SkipSpaces(template, ref i);
                }

                while (i < template.Length && char.IsLetterOrDigit(template[i]) || template[i] == '_')
                {
                    sb.Append(template[i]);
                    i++;
                }

                if (matchCloseBracket)
                {
                    SkipSpaces(template, ref i);

                    if (template[i] != '}')
                        throw new InvalidOperationException($"Invalid Macro definition {sb.ToString()}{template[i]}");
                    i++;
                }

                return sb.ToString();
            }

            return null;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from antman1p

public static void MemDump(string pidString, string memAddrStr)
        {

            int buffWidth = 16;
            int pid;
            int offset = 0x1000;
            int bytesRead = 0;

            Int64 baseAddr;
            var byteArray = new byte[offset];

            // Ensure the input pid is an integer
            try
            {
                pid = Convert.ToInt32(pidString);

            }
            // If not go to the help and alert the user
            catch (Exception ex)
            {
                Console.WriteLine("\nInput not an integer.  Please try again");
                help();
                pid = 0;
            }

            // Ensure the pid is to a running process
            try
            {
                Process proc = Process.GetProcessById(pid);
            }
            // If not go to the help an dinform the user
            catch(Exception ex)
            {
                Console.WriteLine("Not a valid process. \nError: {0}", ex);
                help();
            }

            // Ensure the input is a memory address in hex
            try
            {
                Convert.ToInt64(memAddrStr, 16);
            }
            // if not go to the help and alert the user
            catch (Exception ex)
            {
                Console.WriteLine("\nInvalid Memory address format.  Must be in hex, 0x... format.  \nError: {0}", ex);
                help();
            }

            // Create a new pointer from converting the user input string to a 64 bit integer 
            IntPtr base_mem_address = new IntPtr(Convert.ToInt64(memAddrStr, 16));

            

            try
            {
                // Windows API fucntion call opening the process with desired access level and saving the handle to the process 
                IntPtr pHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_WM_READ, false, pid);

                // Windows API call fucntion to read the process memory into a byte array
                ReadProcessMemory(pHandle, base_mem_address, byteArray, offset, ref bytesRead);

            }
            // If it fails, go to help and alert the user
            catch(Exception ex)
            {
                Console.WriteLine("Unable to dump memory.  \nError: {0}", ex);
                help();
            }

            int position = 0;
            int padding = (buffWidth * 2) + buffWidth;

            Console.WriteLine("\n");

            // Loop to print the memory dump to the consol ein "Hex Dump" typre format
            while (position < offset)
            {
                string line = "";
                line = "0x" + position.ToString("X8") + " ";
                string printBytes = "";
                string text = "";

                for(int i = 0; i < (buffWidth-1); i++)
                {
                    if(position >= offset) { break; }

                    printBytes += byteArray[position].ToString("X2") + " ";

                    if (char.IsLetterOrDigit((char)byteArray[position]) || char.IsPunctuation((char)byteArray[position]) || char.IsSymbol((char)byteArray[position]))
                    {
                        text += (char)byteArray[position];
                    }   
                    else
                    {
                        text += '.';
                    }
                    position++;

                }
                line += printBytes.PadRight(padding, ' ');
                line += " " + text;
                Console.WriteLine(line);

            }
        }

19 Source : AsbStringExtensions.cs
with MIT License
from ARKlab

public static string ToValidAzureServiceBusEnreplacedyName(this string topic)
        {
            return string.Concat(topic
                .Select(c => char.IsLetterOrDigit(c) || c == '/' ? char.ToLower(c) : '_'));
        }

19 Source : ActionWindow.xaml.cs
with GNU General Public License v3.0
from armandoalonso

private void TextEditor_TextEntering(object sender, TextCompositionEventArgs e)
        {
            if (e.Text.Length > 0 && completionWindow != null)
            {
                if (!char.IsLetterOrDigit(e.Text[0]) && !char.IsWhiteSpace(e.Text[0]) && !char.IsSymbol(e.Text[0]))
                {
                    // Whenever a non-letter is typed while the completion window is open,
                    // insert the currently selected element.
                    completionWindow.CompletionList.RequestInsertion(e);
                }
            }
            // Do not set e.Handled=true.
            // We still want to insert the character that was typed.
        }

19 Source : AddonWindow.xaml.cs
with GNU General Public License v3.0
from armandoalonso

private void AddonTextEditor_TextEntering(object sender, TextCompositionEventArgs e)
        {
            if (e.Text.Length > 0 && completionWindow != null)
            {
                if (!char.IsLetterOrDigit(e.Text[0]) && !char.IsWhiteSpace(e.Text[0]) && !char.IsSymbol(e.Text[0]))
                {
                    // Whenever a non-letter is typed while the completion window is open,
                    // insert the currently selected element.
                    completionWindow.CompletionList.RequestInsertion(e);
                }
            }
            // Do not set e.Handled=true.
            // We still want to insert the character that was typed.
        }

19 Source : TextDefineProcessor.cs
with GNU General Public License v3.0
from arycama

public static string ProcessText(string text, Character player, Character npc)
	{
		// Loop through all characters of the original string
		var isReadingDefine = false;
		for(var i = 0; i < text.Length; i++)
		{
			if (isReadingDefine)
			{
				defineBuilder.Append(text[i]);

				if (!char.IsLetterOrDigit(text[i]))
				{
					var currentDefine = defineBuilder.ToString();
					defineBuilder.Clear();
					resultBuilder.Append(ProcessDefineInternal(currentDefine, player, npc));
					isReadingDefine = false;
				}
			}
			else
			{
				if (text[i] == '%')
					isReadingDefine = true;
				else
					resultBuilder.Append(text[i]);
			}
		}

		var result = resultBuilder.ToString();
		resultBuilder.Clear();
		return result;
	}

19 Source : Lexer.cs
with GNU General Public License v2.0
from Asixa

public static Token Scan()
        {
            //remove spaces
            for (; !stream_reader.EndOfStream; ReadChar())
            {
                if (peek == ' ' || peek == '\t')
                {
                }
                else if (peek == '\r')
                {
                    ReadChar();
                    ++line;
                    ch = 0;
                }
                else break;
            }

            if (stream_reader.EndOfStream) return null;

            //remove comments
            if (peek == '/')
            {
                ReadChar();
                switch (peek)
                {
                    case '/':
                        for (;; ReadChar())
                            if (peek == '\r' || peek == '\uffff')
                                return Scan();
                    case '*':
                        for (ReadChar();; ReadChar())
                        {
                            switch (peek)
                            {
                                case '\r':
                                    line++;
                                    ch = 0;
                                    ReadChar();
                                    break;
                                case '*':
                                    ReadChar();
                                    if (peek == '/')
                                    {
                                        ReadChar();
                                        return Scan();
                                    }

                                    break;
                                case '\uffff':
                                    return Scan();
                            }
                        }
                }

                return new Token(TT.SLASH, "/");
            }

            //Operators
            switch (peek)
            {
                case '+': return ReadChar('=') ? Plusreplacedign : Plus;
                case '-': return ReadChar('=') ? Minusreplacedign : Minus;
                case '*': return ReadChar('=') ? Timereplacedign : Time;
                case '/': return ReadChar('=') ? Devidereplacedign : Devide;
                case '&': return ReadChar('&') ? And : BitAnd;
                case '|': return ReadChar('|') ? Or : BitInOr;
                case '=': return ReadChar('=') ? Equal : replacedign;
                case '!': return ReadChar('=') ? NotEqual : Not;
                case '<': return ReadChar('=') ? LessEqual : Less;
                case '>': return ReadChar('=') ? GreaterEqual : Greater;
                case '%': return ReadChar('=') ? Moldingreplacedign : Molding;
                case ':': return ReadChar(':') ?null: Colon;
                case ';':
                    ReadChar(); return Semicolon;
                case ',': ReadChar(); return Comma;
                case '(': ReadChar(); return LeftParentheses;
                case ')': ReadChar(); return RightParentheses;
                case '{': ReadChar(); return LeftBraces;
                case '}': ReadChar(); return RightBraces;
                case '[': ReadChar(); return LeftSquareBracket;
                case ']': ReadChar(); return RightSquareBracket;
                case '.': ReadChar(); return Dot;
                case '#': ReadChar(); return Preprocessor;
                case '^': ReadChar(); return BitExOr;
                case '~': ReadChar(); return Tilde;
            }

            //Digits
            if (char.IsDigit(peek))
            {
                var val = 0;
                do
                {
                    val = 10 * val + (peek - '0');
                    ReadChar();
                } while (char.IsDigit(peek));

                if (peek != '.') return new Token(TT.INTCONSTANT, val.ToString());

                float float_val = val;
                for (float d = 10;; d *= 10)
                {
                    ReadChar();
                    if (!char.IsDigit(peek)) break;
                    float_val += (peek - 48) / d;
                }

                return new Token(TT.FLOATCONSTANT, float_val.ToString(CultureInfo.InvariantCulture));
            }

            //Identifiers
            
            if (char.IsLetter(peek) || peek == '_')
            {
                var s = "";
                do
                {
                    s += peek;
                    ReadChar();
                } while (char.IsLetterOrDigit(peek)||peek=='_');

                //GLSL identifiers starts with "gl_" or contains "__" is not allowed
                if (s.Length >= 3)
                {
                    if (s.Substring(0, 3).ToLower() == "gl_") Error(4);
                    if (s.Contains("__")) Error(3);
                }
                return new Token(Keywords.ContainsKey(s) ? Keywords[s] : TT.IDENTIFIER, s);
            }

           return new Token(TT.UNEXPECTED,peek.ToString());
        }

19 Source : NDesk.Options.cs
with Apache License 2.0
from atifaziz

private static bool IsEolChar (char c)
		{
			return !char.IsLetterOrDigit (c);
		}

19 Source : Tokeniser.cs
with MIT License
from atifaziz

State GetDirectiveName ()
        {
            int start = position;
            for (; position < content.Length; position++) {
                char c = content [position];
                if (!Char.IsLetterOrDigit (c)) {
                    value = content.Substring (start, position - start);
                    return State.Directive;
                }
                nextStateLocation = nextStateLocation.AddCol ();
            }
            throw new ParserException ("Unexpected end of file.", nextStateLocation);
        }

19 Source : XmlHighlightingDefinition.cs
with MIT License
from AvaloniaUI

private static bool IsSimpleWord(string word)
            {
                return char.IsLetterOrDigit(word[0]) && char.IsLetterOrDigit(word, word.Length - 1);
            }

19 Source : IndentationReformatter.cs
with MIT License
from AvaloniaUI

public void Step(IDoreplacedentAccessor doc, IndentationSettings set)
        {
            var line = doc.Text;
            if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
            line = line.TrimStart();

            var indent = new StringBuilder();
            if (line.Length == 0)
            {
                // Special treatment for empty lines:
                if (_blockComment || (_inString && _verbatim))
                    return;
                indent.Append(_block.InnerIndent);
                indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
                
                if (doc.Text != indent.ToString())
                    doc.Text = indent.ToString();
                return;
            }

            if (TrimEnd(doc))
                line = doc.Text.TrimStart();

            var oldBlock = _block;
            var startInComment = _blockComment;
            var startInString = (_inString && _verbatim);

            #region Parse char by char
            _lineComment = false;
            _inChar = false;
            _escape = false;
            if (!_verbatim) _inString = false;

            _lastRealChar = '\n';

            var c = ' ';
            var nextchar = line[0];
            for (var i = 0; i < line.Length; i++)
            {
                if (_lineComment) break; // cancel parsing current line

                var lastchar = c;
                c = nextchar;
                nextchar = i + 1 < line.Length ? line[i + 1] : '\n';

                if (_escape)
                {
                    _escape = false;
                    continue;
                }

                #region Check for comment/string chars
                switch (c)
                {
                    case '/':
                        if (_blockComment && lastchar == '*')
                            _blockComment = false;
                        if (!_inString && !_inChar)
                        {
                            if (!_blockComment && nextchar == '/')
                                _lineComment = true;
                            if (!_lineComment && nextchar == '*')
                                _blockComment = true;
                        }
                        break;
                    case '#':
                        if (!(_inChar || _blockComment || _inString))
                            _lineComment = true;
                        break;
                    case '"':
                        if (!(_inChar || _lineComment || _blockComment))
                        {
                            _inString = !_inString;
                            if (!_inString && _verbatim)
                            {
                                if (nextchar == '"')
                                {
                                    _escape = true; // skip escaped quote
                                    _inString = true;
                                }
                                else
                                {
                                    _verbatim = false;
                                }
                            }
                            else if (_inString && lastchar == '@')
                            {
                                _verbatim = true;
                            }
                        }
                        break;
                    case '\'':
                        if (!(_inString || _lineComment || _blockComment))
                        {
                            _inChar = !_inChar;
                        }
                        break;
                    case '\\':
                        if ((_inString && !_verbatim) || _inChar)
                            _escape = true; // skip next character
                        break;
                }
                #endregion

                if (_lineComment || _blockComment || _inString || _inChar)
                {
                    if (_wordBuilder.Length > 0)
                        _block.LastWord = _wordBuilder.ToString();
                    _wordBuilder.Length = 0;
                    continue;
                }

                if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
                {
                    if (_block.Bracket == '{')
                        _block.Continuation = true;
                }

                if (char.IsLetterOrDigit(c))
                {
                    _wordBuilder.Append(c);
                }
                else
                {
                    if (_wordBuilder.Length > 0)
                        _block.LastWord = _wordBuilder.ToString();
                    _wordBuilder.Length = 0;
                }

                #region Push/Pop the blocks
                switch (c)
                {
                    case '{':
                        _block.ResetOneLineBlock();
                        _blocks.Push(_block);
                        _block.StartLine = doc.LineNumber;
                        if (_block.LastWord == "switch")
                        {
                            _block.Indent(set.IndentString + set.IndentString);
                            /* oldBlock refers to the previous line, not the previous block
							 * The block we want is not available anymore because it was never pushed.
							 * } else if (oldBlock.OneLineBlock) {
							// Inside a one-line-block is another statement
							// with a full block: indent the inner full block
							// by one additional level
							block.Indent(set, set.IndentString + set.IndentString);
							block.OuterIndent += set.IndentString;
							// Indent current line if it starts with the '{' character
							if (i == 0) {
								oldBlock.InnerIndent += set.IndentString;
							}*/
                        }
                        else
                        {
                            _block.Indent(set);
                        }
                        _block.Bracket = '{';
                        break;
                    case '}':
                        while (_block.Bracket != '{')
                        {
                            if (_blocks.Count == 0) break;
                            _block = _blocks.Pop();
                        }
                        if (_blocks.Count == 0) break;
                        _block = _blocks.Pop();
                        _block.Continuation = false;
                        _block.ResetOneLineBlock();
                        break;
                    case '(':
                    case '[':
                        _blocks.Push(_block);
                        if (_block.StartLine == doc.LineNumber)
                            _block.InnerIndent = _block.OuterIndent;
                        else
                            _block.StartLine = doc.LineNumber;
                        _block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
                                     (oldBlock.Continuation ? set.IndentString : "") +
                                     (i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
                        _block.Bracket = c;
                        break;
                    case ')':
                        if (_blocks.Count == 0) break;
                        if (_block.Bracket == '(')
                        {
                            _block = _blocks.Pop();
                            if (IsSingleStatementKeyword(_block.LastWord))
                                _block.Continuation = false;
                        }
                        break;
                    case ']':
                        if (_blocks.Count == 0) break;
                        if (_block.Bracket == '[')
                            _block = _blocks.Pop();
                        break;
                    case ';':
                    case ',':
                        _block.Continuation = false;
                        _block.ResetOneLineBlock();
                        break;
                    case ':':
                        if (_block.LastWord == "case"
                            || line.StartsWith("case ", StringComparison.Ordinal)
                            || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
                        {
                            _block.Continuation = false;
                            _block.ResetOneLineBlock();
                        }
                        break;
                }

                if (!char.IsWhiteSpace(c))
                {
                    // register this char as last char
                    _lastRealChar = c;
                }
                #endregion
            }
            #endregion

            if (_wordBuilder.Length > 0)
                _block.LastWord = _wordBuilder.ToString();
            _wordBuilder.Length = 0;

            if (startInString) return;
            if (startInComment && line[0] != '*') return;
            if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
                return;

            if (line[0] == '}')
            {
                indent.Append(oldBlock.OuterIndent);
                oldBlock.ResetOneLineBlock();
                oldBlock.Continuation = false;
            }
            else
            {
                indent.Append(oldBlock.InnerIndent);
            }

            if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
            {
                indent.Remove(indent.Length - 1, 1);
            }
            else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
            {
                indent.Remove(indent.Length - 1, 1);
            }

            if (line[0] == ':')
            {
                oldBlock.Continuation = true;
            }
            else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
            {
                if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
                    indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
            }
            else if (_lastRealChar == ')')
            {
                if (IsSingleStatementKeyword(_block.LastWord))
                {
                    _block.OneLineBlock++;
                }
            }
            else if (_lastRealChar == 'e' && _block.LastWord == "else")
            {
                _block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
                _block.Continuation = false;
                oldBlock.OneLineBlock = _block.OneLineBlock - 1;
            }

            if (doc.IsReadOnly)
            {
                // We can't change the current line, but we should accept the existing
                // indentation if possible (=if the current statement is not a multiline
                // statement).
                if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
                    oldBlock.StartLine == _block.StartLine &&
                    _block.StartLine < doc.LineNumber && _lastRealChar != ':')
                {
                    // use indent StringBuilder to get the indentation of the current line
                    indent.Length = 0;
                    line = doc.Text; // get untrimmed line
                    foreach (var t in line)
                    {
                        if (!char.IsWhiteSpace(t))
                            break;
                        indent.Append(t);
                    }
                    // /* */ multiline comments have an extra space - do not count it
                    // for the block's indentation.
                    if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
                    {
                        indent.Length -= 1;
                    }
                    _block.InnerIndent = indent.ToString();
                }
                return;
            }

            if (line[0] != '{')
            {
                if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
                    indent.Append(set.IndentString);
                indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
            }

            // this is only for blockcomment lines starting with *,
            // all others keep their old indentation
            if (startInComment)
                indent.Append(' ');

            if (indent.Length != (doc.Text.Length - line.Length) ||
                !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
                char.IsWhiteSpace(doc.Text[indent.Length]))
            {
                doc.Text = indent + line;
            }
        }

19 Source : Utilities.cs
with Apache License 2.0
from aws

public static bool TryGenerateECRRepositoryName(string projectName, out string repositoryName)
        {
            repositoryName = null;
            if (Directory.Exists(projectName))
            {
                projectName = new DirectoryInfo(projectName).Name;
            }
            else if(File.Exists(projectName))
            {
                projectName = Path.GetFileNameWithoutExtension(projectName);
            }

            projectName = projectName.ToLower();
            var sb = new StringBuilder();

            foreach(var c in projectName)
            {
                if(char.IsLetterOrDigit(c))
                {
                    sb.Append(c);
                }
                else if(sb.Length > 0 && (c == '.' || c == '_' || c == '-'))
                {
                    sb.Append(c);
                }
            }

            // Repository name must be at least 2 characters
            if(sb.Length > 1)
            {
                repositoryName = sb.ToString();

                // Max length of repository name is 256 characters.
                if (Constants.MAX_ECR_REPOSITORY_NAME_LENGTH < repositoryName.Length)
                {
                    repositoryName = repositoryName.Substring(0, Constants.MAX_ECR_REPOSITORY_NAME_LENGTH);
                }
            }

            return !string.IsNullOrEmpty(repositoryName);
        }

19 Source : GLSLESPreprocessor.cs
with GNU Lesser General Public License v2.1
from axiom3d

public Token GetToken( bool expand )
		{
			int index = 0;
			char c = this.Source[ index ];
			if ( c == '\n' || this.Source == System.Environment.NewLine )
			{
				this.Line++;
				this.BOL = true;
				if ( c == '\r' )
				{
					index++;
				}
				return new Token( Token.Kind.Newline, this.Source, this.Source.Length - index );
			}
			else if ( Char.IsWhiteSpace( c ) )
			{
				while ( index < this.Source.Length && this.Source[ index ] != '\r' && this.Source[ index ] != '\n' && Char.IsWhiteSpace( this.Source[ index ] ) )
				{
					index++;
				}

				return new Token( Token.Kind.Whitespace, this.Source, index );
			}
			else if ( Char.IsDigit( c ) )
			{
				this.BOL = false;
				if ( c == '0' && this.Source[ 1 ] == 'x' ) //hex numbers
				{
					index++;
					while ( index < this.Source.Length && char.IsNumber( this.Source[ index ] ) )
					{
						index++;
					}
				}
				else
				{
					while ( index < this.Source.Length && Char.IsDigit( this.Source[ index ] ) )
					{
						index++;
					}
				}

				return new Token( Token.Kind.Number, this.Source, index );
			}
			else if ( c == '_' || Char.IsLetterOrDigit( c ) )
			{
				this.BOL = false;

				while ( index < this.Source.Length && ( this.Source[ index ] == '_' || Char.IsLetterOrDigit( this.Source[ index ] ) ) )
				{
					index++;
				}

				return new Token( Token.Kind.Number, this.Source, index );
			}
			else if ( c == '"' || c == '\'' )
			{
				this.BOL = false;
				while ( index < this.Source.Length && this.Source[ index ] != c )
				{
					if ( this.Source[ index ] == '\\' )
					{
						index++;
						if ( index >= this.Source.Length )
						{
							break;
						}
					}
					if ( this.Source[ index ] == '\n' )
					{
						this.Line++;
					}
					index++;
				}
				if ( index < this.Source.Length )
				{
					index++;
				}
				return new Token( Token.Kind.String, this.Source, index );
			}
			else if ( c == '/' && this.Source[ index ] == '/' )
			{
				this.BOL = false;
				index++;
				while ( index < this.Source.Length && this.Source[ index ] != '\r' && this.Source[ index ] != '\n' )
				{
					return new Token( Token.Kind.Linecomment, this.Source, index );
				}
			}
			else if ( c == '/' && this.Source[ index ] == '*' )
			{
				this.BOL = false;
				index++;

				while ( index < this.Source.Length && ( this.Source[ 0 ] != '*' || this.Source[ 1 ] != '/' ) )
				{
					if ( this.Source[ index ] == '\n' )
					{
						this.Line++;
					}
					index++;
				}
				if ( index < this.Source.Length && this.Source[ index ] == '*' )
				{
					index++;
				}
				if ( index < this.Source.Length && this.Source[ index ] == '/' )
				{
					index++;
				}
				return new Token( Token.Kind.Comment, this.Source, index );
			}
			else if ( c == '#' && this.BOL )
			{
				//Skip all whitespaces after '#'
				while ( index < this.Source.Length && Char.IsWhiteSpace( this.Source[ index ] ) )
				{
					index++;
				}
				while ( index < this.Source.Length && !char.IsWhiteSpace( this.Source[ index ] ) )
				{
					index++;
				}
				return new Token( Token.Kind.Directive, this.Source, index );
			}
			else if ( c == '\\' && index < this.Source.Length && ( this.Source[ index ] == '\r' || this.Source[ index ] == '\n' ) )
			{
				//Treat backslash-newline as a whole token
				if ( this.Source[ index ] == '\r' )
				{
					index++;
				}
				if ( this.Source[ index ] == '\n' )
				{
					index++;
				}
				this.Line++;
				this.BOL = true;
				return new Token( Token.Kind.Linecont, this.Source, index );
			}
			else
			{
				this.BOL = false;
				//Handle double-char operators here

				if ( c == '>' && this.Source[ index ] == '>' || this.Source[ index ] == '=' )
				{
					index++;
				}
				else if ( c == '<' && this.Source[ index ] == '<' || this.Source[ index ] == '=' )
				{
					index++;
				}
				else if ( c == '!' && this.Source[ index ] == '=' )
				{
					index++;
				}
				else if ( c == '=' && this.Source[ index ] == '=' )
				{
					index++;
				}
				else if ( ( c == '|' || c == '&' || c == '^' ) && this.Source[ index ] == c )
				{
					index++;
				}

				return new Token( Token.Kind.Punctuation, this.Source, index );
			}

			return Token.Error;
		}

19 Source : AyExpression.cs
with MIT License
from ay2015

public static StringBuilder GetMaskedValue(string ayexpression, string text)
        {
            if (text.IsNull())
            {
                return new StringBuilder();
            }
            //版权引入TODO
            if (ayexpression.IsNull())
            {
                return new StringBuilder(text);
            }
            int ulength = text.Length;
            StringBuilder result = new StringBuilder();
            int uIndex = 0;
            int axlength = ayexpression.Length;
            for (int i = 0; i < axlength; i++)
            {
                if (uIndex >= ulength)
                {
                    int sd = ayexpression.Length - i;
                    if (sd > 0)
                    {
                        string _d = ayexpression.Substring(i, sd);
                        StringBuilder sbNext = new StringBuilder();
                        //检测剩余表达式,直接过滤
                        MatchCollection m0 = Regex.Matches(_d, @"\*\((?<ch>.+)\)");

                        List<string> filterString = new List<string>();
                        foreach (Match match in m0)
                        {
                            GroupCollection groups = match.Groups;
                            filterString.Add(groups[0].Value);
                        }
                        MatchCollection m1 = Regex.Matches(_d, @"\#\((?<ch>.+)\)");
                        foreach (Match match in m1)
                        {
                            GroupCollection groups = match.Groups;
                            filterString.Add(groups[0].Value);
                        }
                        MatchCollection m2 = Regex.Matches(_d, @"\%\((?<ch>.+)\)");
                        foreach (Match match in m2)
                        {
                            GroupCollection groups = match.Groups;
                            filterString.Add(groups[0].Value);
                        }
                        MatchCollection m3 = Regex.Matches(_d, @"\@\((?<ch>.+)\)");
                        foreach (Match match in m3)
                        {
                            GroupCollection groups = match.Groups;
                            filterString.Add(groups[0].Value);
                        }
                        foreach (var item in filterString)
                        {
                            _d = _d.Replace(item, "");
                        }
                        _d = _d.TrimStart(' ').TrimEnd(' ');
                        if (_d.Length > 0)
                        {
                            foreach (var subChar in specChar)
                            {
                                if (subChar == '\\')
                                {
                                    _d = _d.Replace("\\\\", "≌");
                                }
                                else
                                {
                                    _d = _d.Replace("\\" + subChar, "◇");
                                    _d = _d.Replace(subChar.ToString(), "");
                                    _d = _d.Replace("◇", subChar.ToString());
                                }
                            }
                            _d = _d.Replace("≌", "\\");
                        }

                        result.Append(_d);
                    }
                    break;
                }
                char _char = ayexpression[i];
                if (_char == '\\')
                {
                    char next = ayexpression[i + 1];
                    bool isOk = false;
                    foreach (char subChar in specChar)
                    {
                        if (next == subChar)
                        {
                            result.Append(subChar);
                            i++;
                            isOk = true;
                            break;
                        }
                    }
                    if (!isOk)
                    {
                        //判断是不是UL
                        if (next == 'U')
                        {
                            result.Append(char.ToUpper(text[uIndex]));
                            uIndex++;
                            i++;

                        }
                        else if (next == 'L')
                        {
                            result.Append(char.ToLower(text[uIndex]));
                            uIndex++;
                            i++;

                        }
                    }
                }
                else
                {
                    if (_char == '#') //匹配数字
                    {
                        int ds_1 = i + 1;
                        char next = ' ';
                        bool isEnd = false;
                        if (ds_1 == axlength)
                        {
                            isEnd = true;
                        }
                        else
                        {
                            next = ayexpression[i + 1];
                        }

                        if (!isEnd && next == '(')
                        {
                            int nextEndHu = ayexpression.IndexOfAny(new char[] { ')' }, i);
                            if (nextEndHu < 0)
                            {
                                throw new Exception("掩码规则不正确,错误位置:" + i + ",是否少了个右括号?");
                            }
                            string subAd = ayexpression.Substring(i, (nextEndHu - i + 1));
                            MatchCollection matches = Regex.Matches(subAd, @"\#\((?<ch>.+)\)");
                            int xingVal = 0;
                            string xingValue = null;
                            foreach (Match match in matches)
                            {
                                GroupCollection groups = match.Groups;
                                xingValue = groups["ch"].Value;
                                if (string.IsNullOrEmpty(xingValue))
                                {
                                    throw new Exception("#(number)掩码规则出错,错误位置:" + i + ",缺少限定值数字");
                                }
                                xingVal = xingValue.ToInt();
                                if (xingVal == 0)
                                {
                                    throw new Exception("掩码规则不正确,错误位置:" + i + ",括号内数字不能为0或者其他非数字字符");
                                }
                            }
                            for (int mm = 0; mm < xingVal; mm++)
                            {
                                bool _dig = false;
                                for (int j = uIndex; j < ulength; j++)
                                {
                                    if (char.IsDigit(text[j]))
                                    {
                                        _dig = true;
                                        result.Append(text[j]);
                                    }
                                    if (_dig)
                                    {
                                        uIndex++;
                                        break;
                                    }
                                    else
                                    {
                                        uIndex++;
                                    }
                                }
                            }
                            i = i + xingValue.Length + 2;
                        }
                        else
                        {

                            bool _dig = false;
                            for (int j = uIndex; j < ulength; j++)
                            {
                                if (char.IsDigit(text[j]))
                                {
                                    _dig = true;
                                    result.Append(text[j]);
                                }
                                if (_dig)
                                {
                                    uIndex++;
                                    break;
                                }
                                else
                                {
                                    uIndex++;
                                }

                            }
                        }

                    }
                    else if (_char == '@') //匹配字母
                    {

                        int ds_1 = i + 1;
                        char next = ' ';
                        bool isEnd = false;
                        if (ds_1 == axlength)
                        {
                            isEnd = true;
                        }
                        else
                        {
                            next = ayexpression[i + 1];
                        }

                        if (!isEnd && next == '(')
                        {
                            int nextEndHu = ayexpression.IndexOfAny(new char[] { ')' }, i);
                            if (nextEndHu < 0)
                            {
                                throw new Exception("掩码规则不正确,错误位置:" + i + ",是否少了个右括号?");
                            }
                            string subAd = ayexpression.Substring(i, (nextEndHu - i + 1));
                            MatchCollection matches = Regex.Matches(subAd, @"\@\((?<ch>.+)\)");
                            int xingVal = 0;
                            string xingValue = null;
                            foreach (Match match in matches)
                            {
                                GroupCollection groups = match.Groups;
                                xingValue = groups["ch"].Value;
                                if (string.IsNullOrEmpty(xingValue))
                                {
                                    throw new Exception("@(number)掩码规则出错,错误位置:" + i + ",缺少限定值数字");
                                }
                                xingVal = xingValue.ToInt();
                                if (xingVal == 0)
                                {
                                    throw new Exception("掩码规则不正确,错误位置:" + i + ",括号内数字不能为0或者其他非数字字符");
                                }
                            }
                            for (int mm = 0; mm < xingVal; mm++)
                            {
                                bool _dig = false;
                                for (int j = uIndex; j < ulength; j++)
                                {
                                    if (char.IsLetter(text[j]))
                                    {
                                        _dig = true;
                                        result.Append(text[j]);
                                    }
                                    if (_dig)
                                    {
                                        uIndex++;
                                        break;
                                    }
                                    else
                                    {
                                        uIndex++;
                                    }
                                }
                            }
                            i = i + xingValue.Length + 2;

                        }
                        else
                        {
                            bool _dig = false;
                            for (int j = uIndex; j < ulength; j++)
                            {
                                if (char.IsLetter(text[j]))
                                {
                                    _dig = true;
                                    result.Append(text[j]);
                                }
                                if (_dig)
                                {
                                    uIndex++;
                                    break;
                                }
                                else
                                {
                                    uIndex++;
                                }
                            }
                        }
                    }
                    else if (_char == '%') //匹配字母和数字
                    {
                        int ds_1 = i + 1;
                        char next = ' ';
                        bool isEnd = false;
                        if (ds_1 == axlength)
                        {
                            isEnd = true;
                        }
                        else
                        {
                            next = ayexpression[i + 1];
                        }

                        if (!isEnd && next == '(')
                        {
                            int nextEndHu = ayexpression.IndexOfAny(new char[] { ')' }, i);
                            if (nextEndHu < 0)
                            {
                                throw new Exception("掩码规则不正确,错误位置:" + i + ",是否少了个右括号?");
                            }
                            string subAd = ayexpression.Substring(i, (nextEndHu - i + 1));
                            MatchCollection matches = Regex.Matches(subAd, @"\%\((?<ch>.+)\)");
                            int xingVal = 0;
                            string xingValue = null;
                            foreach (Match match in matches)
                            {
                                GroupCollection groups = match.Groups;
                                xingValue = groups["ch"].Value;
                                if (string.IsNullOrEmpty(xingValue))
                                {
                                    throw new Exception("%(number)掩码规则出错,错误位置:" + i + ",缺少限定值数字");
                                }
                                xingVal = xingValue.ToInt();
                                if (xingVal == 0)
                                {
                                    throw new Exception("掩码规则不正确,错误位置:" + i + ",括号内数字不能为0或者其他非数字字符");
                                }
                            }
                            for (int mm = 0; mm < xingVal; mm++)
                            {
                                bool _dig = false;
                                for (int j = uIndex; j < ulength; j++)
                                {
                                    if (char.IsLetterOrDigit(text[j]))
                                    {
                                        _dig = true;
                                        result.Append(text[j]);
                                    }
                                    if (_dig)
                                    {
                                        uIndex++;
                                        break;
                                    }
                                    else
                                    {
                                        uIndex++;
                                    }
                                }
                            }
                            i = i + xingValue.Length + 2;

                        }
                        else
                        {
                            bool _dig = false;
                            for (int j = uIndex; j < ulength; j++)
                            {
                                if (char.IsLetterOrDigit(text[j]))
                                {
                                    _dig = true;
                                    result.Append(text[j]);
                                }
                                if (_dig)
                                {
                                    uIndex++;
                                    break;
                                }
                                else
                                {
                                    uIndex++;
                                }
                            }
                        }
                    }
                    else if (_char == '*') //匹配任意
                    {
                        //判断下一个是不是括号
                        int ds_1 = i + 1;
                        char next = ' ';
                        bool isEnd = false;
                        if (ds_1 == axlength)
                        {
                            isEnd = true;
                        }
                        else
                        {
                            next = ayexpression[i + 1];
                        }

                        if (!isEnd && next == '(')
                        {
                            int nextEndHu = 0;
                            bool isFindRightHu = false;
                            int _i = i;
                            int max_i = 30;
                            int max_i_i = 0;
                            do
                            {
                                nextEndHu = ayexpression.IndexOfAny(new char[] { ')' }, _i);
                                var ch = ayexpression[nextEndHu - 1];
                                if (ch != '\\')
                                {
                                    isFindRightHu = true;
                                }
                                _i = nextEndHu + 1;
                                max_i_i++;
                                if (max_i_i == max_i)
                                {
                                    throw new Exception("掩码规则不正确,错误位置:" + i + ",请检查你的表达式");
                                }
                            } while (!isFindRightHu);

                            if (nextEndHu < 0)
                            {
                                throw new Exception("掩码规则不正确,错误位置:" + i + ",是否少了个右括号?");
                            }
                            string subAd = ayexpression.Substring(i, (nextEndHu - i + 1));
                            MatchCollection matches = Regex.Matches(subAd, @"\*\((?<cha>.+)\)");
                            int xingVal = 0;
                            string xingValue = null;
                            foreach (Match match in matches)
                            {
                                GroupCollection groups = match.Groups;
                                xingValue = groups["cha"].Value;
                                if (string.IsNullOrEmpty(xingValue))
                                {
                                    throw new Exception("*(number)掩码规则出错,错误位置:" + i + ",缺少限定值数字");
                                }

                            }
                            xingVal = xingValue.ToInt();
                            if (xingVal == 0)
                            {
                                if (subAd.Contains(" ^> "))
                                {
                                    string[] _resultString = Regex.Split(xingValue, @" \^> ", RegexOptions.IgnoreCase);
                                    if (_resultString.Length != 2)
                                    {
                                        throw new Exception("*前置替换规则出错,错误位置:" + i);
                                    }
                                    var _r1 = _resultString[0];
                                    string dstr = null;
                                    int _otherLen = ulength - uIndex;
                                    if (_r1 == "?")
                                    {
                                        dstr = text.Substring(uIndex, _otherLen - 1);
                                    }
                                    else
                                    {
                                        dstr = text.Substring(uIndex, Math.Min(_r1.ToInt(), Math.Min(_otherLen, text.Length)));
                                    }
                                    string _d = _resultString[1];
                                    var _d1 = _d.Split('^');
                                    var _d11 = _d1[0];

                                    var _d12 = _d1[1];
                                    var _e1 = Regex.Split(_d12, " -> ", RegexOptions.IgnoreCase);
                                    var _e11 = _e1[0];
                                    var _e12 = _e1[1];
                                    //处理 _e11 和 _e12
                                    foreach (var subChar in specChar)
                                    {
                                        if (subChar == '\\')
                                        {
                                            _e11 = _e11.Replace("\\\\", "≌");
                                            _e12 = _e12.Replace("\\\\", "≌");
                                        }
                                        else
                                        {
                                            _e11 = _e11.Replace("\\" + subChar, "◇");
                                            _e11 = _e11.Replace(subChar.ToString(), "");
                                            _e11 = _e11.Replace("◇", subChar.ToString());

                                            _e12 = _e12.Replace("\\" + subChar, "◇");
                                            _e12 = _e12.Replace(subChar.ToString(), "");
                                            _e12 = _e12.Replace("◇", subChar.ToString());
                                        }
                                    }
                                    _e11 = _e11.Replace("≌", "\\");

                                    if (_d11 == "?")
                                    {
                                        dstr = dstr.Replace(_e11, _e12);
                                        result.Append(dstr);
                                        uIndex = ulength;
                                        i = i + xingValue.Length + 2;
                                    }
                                    else
                                    if (_d11.Contains("+"))  //连续替换
                                    {
                                        string end = dstr;
                                        int _f = (_d11.Substring(1, _d11.Length - 1)).ToInt();
                                        int _f_index = 0;
                                        int _f_count = GetSubStrCountInStr(dstr, _e11, 0).Length;
                                        for (int _g = 0; _g < _f_count; _g++)
                                        {
                                            end = AyReplaceByPlace(end, _e11, _e12, 1);
                                            _f_index++;
                                            if (_f_index == _f)
                                            {
                                                break;
                                            }
                                        }

                                        result.Append(end);

                                        uIndex = ulength;
                                        i = i + xingValue.Length + 2;
                                    }
                                    else //指定第几个替换
                                    {
                                        int _f = _d11.ToInt();
                                        var end = AyReplaceByPlace(dstr, _e11, _e12, _f);
                                        result.Append(end);

                                        uIndex = ulength;
                                        i = i + xingValue.Length + 2;
                                    }
                                }
                                else if (subAd.Contains(" ^< "))  //开始
                                {

                                    string[] _resultString = Regex.Split(xingValue, @" \^< ", RegexOptions.IgnoreCase);
                                    if (_resultString.Length != 2)
                                    {
                                        throw new Exception("*后置替换规则出错,错误位置:" + i);
                                    }
                                    var _r1 = _resultString[0];
                                    string dstr = null;
                                    int _otherLen = ulength - uIndex;
                                    if (_r1 == "?")
                                    {
                                        //dstr = text.Substring(i, _otherLen);
                                        dstr = text.Substring(uIndex, _otherLen);
                                    }
                                    else
                                    {
                                        dstr = text.Substring(uIndex, Math.Min(_r1.ToInt(), Math.Min(_otherLen, text.Length)));
                                    }
                                    string _d = _resultString[1];
                                    var _d1 = _d.Split('^');
                                    var _d11 = _d1[0];

                                    var _d12 = _d1[1];
                                    var _e1 = Regex.Split(_d12, " -> ", RegexOptions.IgnoreCase);
                                    var _e11 = _e1[0];
                                    var _e12 = _e1[1];
                                    //处理 _e11 和 _e12
                                    foreach (var subChar in specChar)
                                    {
                                        if (subChar == '\\')
                                        {
                                            _e11 = _e11.Replace("\\\\", "≌");
                                            _e12 = _e12.Replace("\\\\", "≌");
                                        }
                                        else
                                        {
                                            _e11 = _e11.Replace("\\" + subChar, "◇");
                                            _e11 = _e11.Replace(subChar.ToString(), "");
                                            _e11 = _e11.Replace("◇", subChar.ToString());

                                            _e12 = _e12.Replace("\\" + subChar, "◇");
                                            _e12 = _e12.Replace(subChar.ToString(), "");
                                            _e12 = _e12.Replace("◇", subChar.ToString());
                                        }
                                    }
                                    _e11 = _e11.Replace("≌", "\\");



                                    if (_d11 == "?")
                                    {
                                        dstr = dstr.Replace(_e11, _e12);
                                        result.Append(dstr);
                                        uIndex = ulength;
                                        i = i + xingValue.Length + 2;
                                    }
                                    else
                                    if (_d11.Contains("+"))  //连续替换
                                    {
                                        string end = dstr;
                                        int _f = (_d11.Substring(1, _d11.Length - 1)).ToInt();  // 连续次数
                                        int _f_count = GetSubStrCountInStr(dstr, _e11, 0).Length;
                                        if (_f_count == 0) { }
                                        else if (_f_count <= _f)
                                        {
                                            dstr = dstr.Replace(_e11, _e12);
                                            result.Append(dstr);
                                            uIndex = ulength;
                                            i = i + xingValue.Length + 2;
                                        }
                                        else
                                        {
                                            for (int _g = 0; _g < _f; _g++)
                                            {
                                                end = AyReplaceByPlace(end, _e11, _e12, _f_count--);
                                            }
                                        }

                                        result.Append(end);
                                        uIndex = ulength;
                                        i = i + xingValue.Length + 2;
                                    }
                                    else //指定第几个替换
                                    {
                                        int _f = _d11.ToInt();
                                        int _f_count = GetSubStrCountInStr(dstr, _e11, 0).Length;
                                        if (_f_count == 0 || _f_count <= _f)
                                        {
                                            result.Append(dstr);
                                            uIndex = ulength;
                                            i = i + xingValue.Length + 2;
                                        }
                                        else
                                        {
                                            var end = AyReplaceByPlace(dstr, _e11, _e12, (_f_count - _f + 1));
                                            result.Append(end);
                                            uIndex = ulength;
                                            i = i + xingValue.Length + 2;
                                        }
                                    }
                                }
                                else   //正常替换
                                {

                                    if (xingValue.IndexOf(" -> ") < 0)
                                    {
                                        if (xingValue == "?")
                                        {
                                            int utlen = ulength - uIndex;
                                            result.Append(text.Substring(uIndex, utlen));
                                            uIndex = ulength;
                                            //掩码跳过位数()+值的length;
                                            i = i + xingValue.Length + 2;
                                        }
                                        else
                                        {
                                            throw new Exception("*(规则) 掩码规则出错,错误位置:" + i + ",限定值不合法");
                                        }

                                    }

                                    else
                                    {
                                        string[] _resultString = Regex.Split(xingValue, " -> ", RegexOptions.IgnoreCase);
                                        string _d = _resultString[1];
                                        foreach (var subChar in specChar)
                                        {
                                            if (subChar == '\\')
                                            {
                                                _d = _d.Replace("\\\\", "≌");
                                            }
                                            else
                                            {
                                                _d = _d.Replace("\\" + subChar, "◇");
                                                _d = _d.Replace(subChar.ToString(), "");
                                                _d = _d.Replace("◇", subChar.ToString());
                                            }
                                        }
                                        _d = _d.Replace("≌", "\\");

                                        if (_resultString[0] == "?")
                                        {
                                            int utlen = ulength - uIndex;
                                            StringBuilder sb1 = new StringBuilder();
                                            for (int k = 0; k < utlen; k++)
                                            {
                                                sb1.Append(_d);
                                            }
                                            result.Append(sb1.ToString());

                                            uIndex = ulength;
                                            //掩码跳过位数()+值的length;
                                            i = i + xingValue.Length + 2;
                                        }
                                        else
                                        {
                                            int _ind = _resultString[0].ToInt();
                                            int utlen = ulength - uIndex;
                                            int minXin = Math.Min(_ind, utlen);
                                            StringBuilder sb1 = new StringBuilder();
                                            for (int k = 0; k < _ind; k++)
                                            {
                                                sb1.Append(_d);
                                            }
                                            result.Append(sb1.ToString());
                                            if (minXin == utlen) break; //如果要取的字符已经不够了,下次直接终止掩码过程了
                                            uIndex = uIndex + minXin;
                                            //掩码跳过位数()+值的length;
                                            i = i + xingValue.Length + 2;
                                        }
                                    }

                                }

                            }
                            else
                            {
                                int utlen = ulength - uIndex;
                                int minXin = Math.Min(xingVal, utlen);
                                result.Append(text.Substring(uIndex, minXin));
                                if (minXin == utlen) break; //如果要取的字符已经不够了,下次直接终止掩码过程了
                                uIndex = uIndex + minXin;
                                //掩码跳过位数()+值的length;
                                i = i + xingValue.Length + 2;
                            }
                        }
                        else
                        {
                            result.Append(text[uIndex]);
                            uIndex++;
                        }

                    }
                    else if (_char == '$') //终止
                    {
                        break;
                    }
                    else
                    {
                        result.Append(_char);
                    }
                }
            }
            return result;
        }

19 Source : XMLConfiguration.cs
with MIT License
from azist

protected override string AdjustNodeName(string name)
    {
      var result = new StringBuilder(32);//average id size is 16-20 chars

      foreach (var c in name)
        if (char.IsLetterOrDigit(c) || c == '_' || c == '.')
          result.Append(c);
        else
          result.Append('-');

      return result.ToString();
    }

19 Source : Compiler.cs
with MIT License
from azist

public string EscapeFileName(string fn)
            {
                var result = new StringBuilder();

                foreach(var c in fn)
                {
                    if ( char.IsLetterOrDigit(c) || c=='-' || c=='_' || c=='.') result.Append(c);
                    else
                      result.Append('_');
                }

                return result.ToString();
            }

19 Source : Sources.cs
with MIT License
from azist

public string InferClreplacedName()
      {
          var name = Path.GetFileNameWithoutExtension(FileName).Trim();

          var result = new StringBuilder(name.Length);
          var first = true;
          foreach(var c in name)
          {
             if ((first && !char.IsLetter(c)) || !char.IsLetterOrDigit(c))
                result.Append("_");
             else
                result.Append(c);

             first = false;
          }

          return result.ToString();
      }

19 Source : DataEntryUtils.cs
with MIT License
from azist

public static bool CheckEMail(string email)
    {
      if (email.IsNullOrWhiteSpace()) return false;

      var lastPos = email.Length - 1;

      var atPos = email.IndexOf('@');
      if (atPos <= 0 || atPos == lastPos)
        return false;

      char c;

      // local part
      var prevIsDot = false;
      var end = atPos - 1;
      for (int i = 0; i <= end; i++)
      {
        c = email[i];
        if (i == 0 || i == end)
        {
          if (!IsValidEMailLocalPartChar(c)) return false;
          continue;
        }
        if (c == '.')
        {
          if (prevIsDot) return false;
          prevIsDot = true;
        }
        else
        {
          if (!IsValidEMailLocalPartChar(c)) return false;
          prevIsDot = false;
        }
      }

      // domain part
      var prevIsHyphen = false;
      prevIsDot = false;
      var start = atPos + 1;
      end = lastPos;
      for (int i = start; i <= end; i++)
      {
        c = email[i];
        if (i == start || i == end)
        {
          if (!Char.IsLetterOrDigit(c)) return false;
          continue;
        }
        if (c == '.')
        {
          if (prevIsDot || prevIsHyphen) return false;
          prevIsDot = true;
          continue;
        }
        if (c == '-')
        {
          if (prevIsDot) return false;
          prevIsHyphen = true;
          continue;
        }
        if (!Char.IsLetterOrDigit(c)) return false;
        prevIsDot = false;
        prevIsHyphen = false;
      }
      return true;
    }

19 Source : NaturalTextGenerator.cs
with MIT License
from azist

private static bool filter(char chr)
    {
      return chr=='\'' || chr=='-' || Char.IsLetterOrDigit(chr);
    }

19 Source : CoreUtils.cs
with MIT License
from azist

public static bool IsValidXMLName(this string name)
    {
      if (name.IsNullOrWhiteSpace()) return false;
      for (int i = 0; i < name.Length; i++)
      {
        char c = name[i];
        if (c == '-' || c == '_') continue;
        if (!Char.IsLetterOrDigit(c) || (i == 0 && !Char.IsLetter(c))) return false;
      }

      return true;
    }

19 Source : NaturalTextGenerator.cs
with MIT License
from azist

private static void scrollToWordStart(string text, ref int i)
    {
      while(true)
      {
        var chr = text[i];
        if (chr==' ' || chr=='.' || chr==',' || chr=='?' || chr=='!' || chr=='\r' || chr=='\n') break;

        i++;
        if (i==text.Length) i=0;
      }

      while(!Char.IsLetterOrDigit(text[i]))
      {
        i++;
        if (i==text.Length) i=0;
      }
    }

19 Source : WebUtils.cs
with MIT License
from azist

public static bool IsValidJSIdentifier(this string id)
    {
      if (id.IsNullOrWhiteSpace()) return false;

      if (JS_RESERVED_WORDS.Contains(id)) return false;

      for (int i = 0; i < id.Length; i++)
      {
        char c = id[i];
        if (c == '$' || c == '_') continue;
        if (!Char.IsLetterOrDigit(c) || (i == 0 && !Char.IsLetter(c))) return false;
      }

      return true;
    }

19 Source : DataEntryUtils.cs
with MIT License
from azist

[MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool IsValidEMailLocalPartChar(char c)
    {
      const string validLocalPartChars = "!#$%&'*+-/=?^_`{|}~";
      return (Char.IsLetterOrDigit(c) || validLocalPartChars.IndexOf(c) >= 0);
    }

19 Source : DataEntryUtils.cs
with MIT License
from azist

public static string NormalizeUSPhone(string value)
    {
      if (value == null) return null;

      value = value.Trim();

      if (value.Length == 0) return value;


      bool isArea = false;
      bool isExt = false;

      string area = string.Empty;
      string number = string.Empty;
      string ext = string.Empty;


      if (value.StartsWith("+")) //international phone, just return as-is
        return value;

      Char chr;
      for (int i = 0; i < value.Length; i++)
      {
        chr = value[i];

        if (!isArea && chr == '(' && area.Length == 0)
        {
          isArea = true;
          continue;
        }

        if (isArea && chr == ')')
        {
          isArea = false;
          continue;
        }

        if (isArea && area.Length == 3)
          isArea = false;


        if (number.Length > 0 && !isExt)
        {  //check extension
          if (chr == 'x' || chr == 'X' || (chr == '.' && number.Length>6))
          {
            isExt = true;
            continue;
          }
          string trailer = value.Substring(i).ToUpperInvariant();

          if (trailer.StartsWith("EXT") && number.Length >= 7)
          {
            isExt = true;
            i += 2;
            continue;
          }
          if (trailer.StartsWith("EXT.") && number.Length >= 7)
          {
            isExt = true;
            i += 3;
            continue;
          }

        }

        if (!Char.IsLetterOrDigit(chr)) continue;


        if (isArea)
          area += chr;
        else
          if (isExt)
            ext += chr;
          else
            number += chr;
      }

      while (number.Length < 7)
        number += '?';

      if (area.Length == 0)
      {
        if (number.Length >= 10)
        {
          area = number.Substring(0, 3);
          number = number.Substring(3);
        }
        else
          area = "???";
      }

      if (number.Length > 7 && ext.Length == 0)
      {
        ext = number.Substring(7);
        number = number.Substring(0, 7);
      }

      number = number.Substring(0, 3) + "-" + number.Substring(3);

      if (ext.Length > 0) ext = "x" + ext;

      return string.Format("({0}) {1}{2}", area, number, ext);
    }

19 Source : TypeLookupHandler.cs
with MIT License
from azist

private bool isValidTypeNameKey(string key)
            {
              if (key==null) return false;

              for(var i=0; i<key.Length; i++)
              {
                var c = key[i];
                if (char.IsLetterOrDigit(c)) continue;
                if (c=='/' || c=='\\' || c=='-' || c=='_' || c=='.') continue;
                return false;
              }

              return true;
            }

19 Source : GenericLexer.cs
with MIT License
from b3b00

public void AddStringLexem(IN token,  BuildResult<ILexer<IN>> result , string stringDelimiter,
            string escapeDelimiterChar = "\\")
        {
            if (string.IsNullOrEmpty(stringDelimiter) || stringDelimiter.Length > 1)
                result.AddError(new LexerInitializationError(ErrorLevel.FATAL,
                    I18N.Instance.GetText(I18n,Message.StringDelimiterMustBe1Char,stringDelimiter,token.ToString()),
                    ErrorCodes.LEXER_STRING_DELIMITER_MUST_BE_1_CHAR));
            if (stringDelimiter.Length == 1 && char.IsLetterOrDigit(stringDelimiter[0]))
                result.AddError(new InitializationError(ErrorLevel.FATAL,
                    I18N.Instance.GetText(I18n,Message.StringDelimiterCannotBeLetterOrDigit,stringDelimiter,token.ToString()),
                    ErrorCodes.LEXER_STRING_DELIMITER_CANNOT_BE_LETTER_OR_DIGIT));

            if (string.IsNullOrEmpty(escapeDelimiterChar) || escapeDelimiterChar.Length > 1)
                result.AddError(new InitializationError(ErrorLevel.FATAL,
                    I18N.Instance.GetText(I18n,Message.StringEscapeCharMustBe1Char,escapeDelimiterChar,token.ToString()),
                    ErrorCodes.LEXER_STRING_ESCAPE_CHAR_MUST_BE_1_CHAR));
            if (escapeDelimiterChar.Length == 1 && char.IsLetterOrDigit(escapeDelimiterChar[0]))
                result.AddError(new InitializationError(ErrorLevel.FATAL,
                    I18N.Instance.GetText(I18n,Message.StringEscapeCharCannotBeLetterOrDigit,escapeDelimiterChar,token.ToString()),
                    ErrorCodes.LEXER_STRING_ESCAPE_CHAR_CANNOT_BE_LETTER_OR_DIGIT));

            StringDelimiterChar = (char)0;
            var stringDelimiterChar = (char)0;

            EscapeStringDelimiterChar = (char)0;
            var escapeStringDelimiterChar = (char)0;
            
            if (stringDelimiter.Length == 1)
            {
                StringCounter++;

                StringDelimiterChar = stringDelimiter[0];
                stringDelimiterChar = stringDelimiter[0];

                EscapeStringDelimiterChar = escapeDelimiterChar[0];
                escapeStringDelimiterChar = escapeDelimiterChar[0];
            }


            NodeCallback<GenericToken> callback = match =>
            {
                match.Properties[DerivedToken] = token;
                var value = match.Result.SpanValue;

                match.Result.SpanValue = value;

                match.StringDelimiterChar = stringDelimiterChar;
                match.IsString = true;
                if (stringDelimiterChar != escapeStringDelimiterChar)
                {
                    match.Result.SpanValue = diffCharEscaper(escapeStringDelimiterChar,stringDelimiterChar, match.Result.SpanValue);
                }
                else
                {                   
                    match.Result.SpanValue = sameCharEscaper(escapeStringDelimiterChar,stringDelimiterChar, match.Result.SpanValue);
                }

                return match;
            };

            if (stringDelimiterChar != escapeStringDelimiterChar)
            {

                FSMBuilder.GoTo(start);
                FSMBuilder.Transition(stringDelimiterChar)
                    .Mark(in_string + StringCounter)
                    .ExceptTransitionTo(new[] { stringDelimiterChar, escapeStringDelimiterChar },
                        in_string + StringCounter)
                    .Transition(escapeStringDelimiterChar)
                    .Mark(escape_string + StringCounter)
                    .ExceptTransitionTo(new[] { stringDelimiterChar }, in_string + StringCounter)
                    .GoTo(escape_string + StringCounter)
                    .TransitionTo(stringDelimiterChar, in_string + StringCounter)
                    .Transition(stringDelimiterChar)
                    .End(GenericToken.String)
                    .Mark(string_end + StringCounter)
                    .CallBack(callback);
                FSMBuilder.Fsm.StringDelimiter = stringDelimiterChar;
            }
            else
            {
                var exceptDelimiter = new[] { stringDelimiterChar };
                var in_string = "in_string_same";
                var escaped = "escaped_same";
                var delim = "delim_same";

                FSMBuilder.GoTo(start)
                    .Transition(stringDelimiterChar)
                    .Mark(in_string + StringCounter)
                    .ExceptTransitionTo(exceptDelimiter, in_string + StringCounter)
                    .Transition(stringDelimiterChar)
                    .Mark(escaped + StringCounter)
                    .End(GenericToken.String)
                    .CallBack(callback)
                    .Transition(stringDelimiterChar)
                    .Mark(delim + StringCounter)
                    .ExceptTransitionTo(exceptDelimiter, in_string + StringCounter);

                FSMBuilder.GoTo(delim + StringCounter)
                    .TransitionTo(stringDelimiterChar, escaped + StringCounter)
                    .ExceptTransitionTo(exceptDelimiter, in_string + StringCounter);
            }
        }

See More Examples