Here are the examples of the csharp api char.IsLetter(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
543 Examples
19
View Source File : PgSqlBuilder.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public override bool VisitExprTableFullName(ExprTableFullName exprTableFullName, IExpr? parent)
{
if (exprTableFullName.DbSchema != null &&
exprTableFullName.DbSchema.Schema.LowerInvariantName == "information_schema" &&
exprTableFullName.DbSchema.Database == null &&
IsSafeName(exprTableFullName.TableName.Name))
{
//Preventing quoting
this.Builder.Append(exprTableFullName.DbSchema.Schema.Name);
this.Builder.Append('.');
this.Builder.Append(exprTableFullName.TableName.Name);
return true;
}
return this.VisitExprTableFullNameCommon(exprTableFullName, parent);
bool IsSafeName(string name)
{
for (var index = 0; index < name.Length; index++)
{
char ch = name[index];
if (index == 0 && !char.IsLetter(ch))
{
return false;
}
if (!char.IsLetter(ch) && ch != '_')
{
return false;
}
}
return true;
}
}
19
View Source File : StringExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static string ToProperCase(this string value)
{
// If there are 0 or 1 characters, just return the string.
if (value == null) { return value; }
if (value.Length < 2) { return value.ToUpper(); }
// If there's already spaces in the string, return.
if (value.Contains(" ")) { return value; }
// Start with the first character.
string result = value.Substring(0, 1).ToUpper();
// Add the remaining characters.
for (int i = 1; i < value.Length; i++)
{
if (char.IsLetter(value[i]) &&
char.IsUpper(value[i]))
{
// Add a space if the previous character is not upper-case.
// e.g. "LeftHand" -> "Left Hand"
if (i != 1 && // First character is upper-case in result.
(!char.IsLetter(value[i - 1]) || char.IsLower(value[i - 1])))
{
result += " ";
}
// If previous character is upper-case, only add space if the next
// character is lower-case. Otherwise replacedume this character to be inside
// an acronym.
// e.g. "OpenVRLeftHand" -> "Open VR Left Hand"
else if (i < value.Length - 1 &&
char.IsLetter(value[i + 1]) && char.IsLower(value[i + 1]))
{
result += " ";
}
}
result += value[i];
}
return result;
}
19
View Source File : ParentLexer.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
public override MergableLexerResult GetNextToken(ITextBufferReader reader, ILexicalState lexicalState) {
// Initialize
int tokenId = ParentTokenId.Invalid;
// Get the next character
char ch = reader.Read();
switch (lexicalState.Id) {
case ParentLexicalStateId.Default: {
// If the character is a letter or digit...
if ((Char.IsLetter(ch) || (ch == '_'))) {
// Parse the identifier
tokenId = this.ParseIdentifier(reader, ch);
}
else if (Char.IsWhiteSpace(ch)) {
// Consume sequential whitespace
while (Char.IsWhiteSpace(reader.Peek()))
reader.Read();
tokenId = ParentTokenId.Whitespace;
}
else {
// Invalid
tokenId = ParentTokenId.Invalid;
}
break;
}
}
if (tokenId != ParentTokenId.Invalid) {
return new MergableLexerResult(MatchType.ExactMatch, new LexicalStateTokenData(lexicalState, tokenId));
}
else {
reader.ReadReverse();
return MergableLexerResult.NoMatch;
}
}
19
View Source File : SimpleLexer.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
public override MergableLexerResult GetNextToken(ITextBufferReader reader, ILexicalState lexicalState) {
// Initialize
int tokenId = SimpleTokenId.Invalid;
// Get the next character
char ch = reader.Read();
// If the character is a letter or digit...
if ((Char.IsLetter(ch) || (ch == '_'))) {
// Parse the identifier
tokenId = this.ParseIdentifier(reader, ch);
}
else if ((ch != '\n') && (Char.IsWhiteSpace(ch))) {
while ((reader.Peek() != '\n') && (Char.IsWhiteSpace(reader.Peek())))
reader.Read();
tokenId = SimpleTokenId.Whitespace;
}
else {
tokenId = SimpleTokenId.Invalid;
switch (ch) {
case ',':
tokenId = SimpleTokenId.Comma;
break;
case '(':
tokenId = SimpleTokenId.OpenParenthesis;
break;
case ')':
tokenId = SimpleTokenId.CloseParenthesis;
break;
case ';':
tokenId = SimpleTokenId.SemiColon;
break;
case '\n':
// Line terminator
tokenId = SimpleTokenId.Whitespace;
break;
case '{':
tokenId = SimpleTokenId.OpenCurlyBrace;
break;
case '}':
tokenId = SimpleTokenId.CloseCurlyBrace;
break;
case '/':
tokenId = SimpleTokenId.Division;
switch (reader.Peek()) {
case '/':
// Parse a single-line comment
tokenId = this.ParseSingleLineComment(reader);
break;
case '*':
// Parse a multi-line comment
tokenId = this.ParseMultiLineComment(reader);
break;
}
break;
case '=':
if (reader.Peek() == '=') {
reader.Read();
tokenId = SimpleTokenId.Equality;
}
else
tokenId = SimpleTokenId.replacedignment;
break;
case '!':
if (reader.Peek() == '=') {
reader.Read();
tokenId = SimpleTokenId.Inequality;
}
break;
case '+':
tokenId = SimpleTokenId.Addition;
break;
case '-':
tokenId = SimpleTokenId.Subtraction;
break;
case '*':
tokenId = SimpleTokenId.Multiplication;
break;
default:
if ((ch >= '0') && (ch <= '9')) {
// Parse the number
tokenId = this.ParseNumber(reader, ch);
}
break;
}
}
if (tokenId != SimpleTokenId.Invalid) {
return new MergableLexerResult(MatchType.ExactMatch, new LexicalStateTokenData(lexicalState, tokenId));
}
else {
reader.ReadReverse();
return MergableLexerResult.NoMatch;
}
}
19
View Source File : SimpleLexer.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : 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
View Source File : DateTimePicker.xaml.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
private int CalcPosition(int selStart, Direction direction)
{
string df = DateFormat;
if (selStart >= df.Length)
selStart = df.Length - 1;
char startChar = df[selStart];
int i = selStart;
for (; ; )
{
i += (int)direction;
if ((uint)i >= (uint)df.Length)
return -1;
if (df[i] == startChar)
continue;
if (char.IsLetter(df[i]))
break;
startChar = '\0'; // to handle cases like "yyyy-MM-dd (ddd)" correctly
}
if (direction < 0)
// move to the beginning of the field
while (i > 0 && df[i - 1] == df[i])
i--;
return i;
}
19
View Source File : DateTimePicker.xaml.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
private bool FocusOnDatePart(int selStart)
{
ReformatDateText();
// Find beginning of field to select
string df = DateFormat;
if (selStart > df.Length - 1)
selStart = df.Length - 1;
char firstchar = df[selStart];
while (!char.IsLetter(firstchar) && selStart + 1 < df.Length)
{
selStart++;
firstchar = df[selStart];
}
while (selStart > 0 && df[selStart - 1] == firstchar)
selStart--;
int selLength = 1;
while (selStart + selLength < df.Length && df[selStart + selLength] == firstchar)
selLength++;
// don't select AM/PM: we have no interface to change it.
if (firstchar == 't')
return false;
DateDisplay.Focus();
DateDisplay.Select(selStart, selLength);
return true;
}
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr
License : GNU General Public License v2.0
Project Creator : adrifcastr
public async void decryptbsgnca()
{
offbtn();
startbar();
statuslabel.Content = "Decrypting Base Game NCA...";
string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
var di = new DirectoryInfo(tmpdir);
var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
var larbnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();
string basenca = String.Join(" ", larbnca);
string nspddir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
string replacedlkeyp = bsgreplacedlkyinput.Text;
string bsgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
string arg1 = @"-k keys.txt " + "--replacedlekey=" + bsgtk + " " + basenca;
string arg2 = " --plaintext=" + tmpdir + "\\NCAID_PLAIN.nca";
string arg = arg1 + arg2;
Process decrnca = new Process();
decrnca.StartInfo.FileName = nspddir;
decrnca.StartInfo.Arguments = arg;
decrnca.StartInfo.CreateNoWindow = true;
decrnca.StartInfo.UseShellExecute = false;
decrnca.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
decrnca.EnableRaisingEvents = true;
decrnca.Start();
await Task.Run(() => decrnca.WaitForExit());
decrnca.Close();
extractncau();
}
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr
License : GNU General Public License v2.0
Project Creator : adrifcastr
public async void applyupdate()
{
statuslabel.Content = "Merging NCA's...";
string curdir = AppDomain.CurrentDomain.BaseDirectory;
string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
string upddir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
string nspudir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
string basenca = tmpdir + "\\NCAID_PLAIN.nca";
var di = new DirectoryInfo(upddir);
var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
var larupdnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();
string updnca = String.Join(" ", larupdnca);
string replacedlkeyp = updreplacedlkyinput.Text;
string upgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
string arg1 = @"-k keys.txt " + "--replacedlekey=" + upgtk + " --basenca=" + basenca + " --section1=" + curdir + "\\romfs.bin" + " --exefsdir=";
string arg2 = tmpdir + "\\exefs " + updnca;
string arg = arg1 + arg2;
Process aplupd = new Process();
aplupd.StartInfo.FileName = nspudir;
aplupd.StartInfo.Arguments = arg;
aplupd.StartInfo.CreateNoWindow = true;
aplupd.StartInfo.UseShellExecute = false;
aplupd.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
aplupd.EnableRaisingEvents = true;
aplupd.Start();
await Task.Run(() => aplupd.WaitForExit());
aplupd.Close();
stopbar();
statuslabel.Content = "";
Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);
Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\upd", true);
onbtn();
System.Windows.MessageBox.Show("Update applyment finished.\nYou can now use your updated romFS via fs-mitm.");
}
19
View Source File : IdentifierParser.cs
License : MIT License
Project Creator : AgathokakologicalBit
License : MIT License
Project Creator : AgathokakologicalBit
private static bool IsMatching(char c, Tokenizer.State state)
{
const string possible = @"[email protected]#$%,^&|*/\_+~-<=>";
if (Char.IsLetter(c) || possible.Contains(c))
{
if (c > 127)
{
// If identifier contains non-ascii letters
// it will be written as error to state
state.ErrorCode = (uint)ErrorCodes.T_InvalidIdentifier;
state.ErrorMessage =
"Identifier can contains only:\n" +
" - latin letters\n" +
$" - '{possible}' symbols";
}
return true;
}
return false;
}
19
View Source File : ZeroDiscover.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void ReadEnreplacedy(TypeDoreplacedent typeDoreplacedent, Type type)
{
if (type == null || type.IsAutoClreplaced || !IsLetter(type.Name[0]) ||
type.IsInterface || type.IsMarshalByRef || type.IsCOMObject ||
type == typeof(object) || type == typeof(void) ||
type == typeof(ValueType) || type == typeof(Type) || type == typeof(Enum) ||
type.Namespace == "System" || type.Namespace?.Contains("System.") == true)
return;
if (typeDocs.TryGetValue(type, out var doc))
{
foreach (var field in doc.Fields)
{
if (typeDoreplacedent.Fields.ContainsKey(field.Key))
typeDoreplacedent.Fields[field.Key] = field.Value;
else
typeDoreplacedent.Fields.Add(field.Key, field.Value);
}
return;
}
if (typeDocs2.TryGetValue(type, out var _))
{
ZeroTrace.WriteError("ReadEnreplacedy", "over flow", type.Name);
return;
}
typeDocs2.Add(type, typeDoreplacedent);
if (type.IsArray)
{
ReadEnreplacedy(typeDoreplacedent, type.replacedembly.GetType(type.FullName.Split('[')[0]));
return;
}
if (type.IsGenericType && !type.IsValueType &&
type.GetGenericTypeDefinition().GetInterface(typeof(IEnumerable<>).FullName) != null)
{
ReadEnreplacedy(typeDoreplacedent, type.GetGenericArguments().Last());
return;
}
XmlMember.Find(type);
if (type.IsEnum)
{
foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
{
if (field.IsSpecialName)
{
continue;
}
var info = CheckMember(typeDoreplacedent, type, field, field.FieldType, false, false, false);
if (info != null)
{
info.TypeName = "int";
info.Example = ((int)field.GetValue(null)).ToString();
info.JsonName = null;
}
}
typeDocs.Add(type, new TypeDoreplacedent
{
fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
});
typeDoreplacedent.Copy(XmlMember.Find(type));
return;
}
var dc = type.GetAttribute<DataContractAttribute>();
var jo = type.GetAttribute<JsonObjectAttribute>();
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
if (property.IsSpecialName)
{
continue;
}
CheckMember(typeDoreplacedent, type, property, property.PropertyType, jo != null, dc != null);
}
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
if (!char.IsLetter(field.Name[0]) || field.IsSpecialName)
{
continue;
}
CheckMember(typeDoreplacedent, type, field, field.FieldType, jo != null, dc != null);
}
typeDocs.Add(type, new TypeDoreplacedent
{
fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
});
typeDoreplacedent.Copy(XmlMember.Find(type));
}
19
View Source File : KickassParser.cs
License : MIT License
Project Creator : aivarasatk
License : MIT License
Project Creator : aivarasatk
private DateTime ParseDate(string date)
{
var digitEndIndex = 0;
foreach(var c in date)
{
if (char.IsLetter(c))
break;
digitEndIndex++;
}
int.TryParse(date.Substring(0, digitEndIndex), out var numberToSubtract);
var parsedDate = DateTime.UtcNow;
if (date.Contains("min.")) parsedDate = parsedDate.AddMinutes(-numberToSubtract);
if (date.Contains("hour")) parsedDate = parsedDate.AddHours(-numberToSubtract);
if (date.Contains("day")) parsedDate = parsedDate.AddDays(-numberToSubtract);
if (date.Contains("month")) parsedDate = parsedDate.AddMonths(-numberToSubtract);
if (date.Contains("year")) parsedDate = parsedDate.AddYears(-numberToSubtract);
return parsedDate;
}
19
View Source File : HtmlLexicalAnalyzer.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
private void GetNextCharacter()
{
if (_nextCharacterCode == -1)
{
throw new InvalidOperationException("GetNextCharacter method called at the end of a stream");
}
_previousCharacter = _nextCharacter;
_nextCharacter = _lookAheadCharacter;
_nextCharacterCode = _lookAheadCharacterCode;
// next character not an enreplacedy as of now
_isNextCharacterEnreplacedy = false;
this.ReadLookAheadCharacter();
if (_nextCharacter == '&')
{
if (_lookAheadCharacter == '#')
{
// numeric enreplacedy - parse digits - &#DDDDD;
int enreplacedyCode;
enreplacedyCode = 0;
this.ReadLookAheadCharacter();
// largest numeric enreplacedy is 7 characters
for (int i = 0; i < 7 && Char.IsDigit(_lookAheadCharacter); i++)
{
enreplacedyCode = 10 * enreplacedyCode + (_lookAheadCharacterCode - (int)'0');
this.ReadLookAheadCharacter();
}
if (_lookAheadCharacter == ';')
{
// correct format - advance
this.ReadLookAheadCharacter();
_nextCharacterCode = enreplacedyCode;
// if this is out of range it will set the character to '?'
_nextCharacter = (char)_nextCharacterCode;
// as far as we are concerned, this is an enreplacedy
_isNextCharacterEnreplacedy = true;
}
else
{
// not an enreplacedy, set next character to the current lookahread character
// we would have eaten up some digits
_nextCharacter = _lookAheadCharacter;
_nextCharacterCode = _lookAheadCharacterCode;
this.ReadLookAheadCharacter();
_isNextCharacterEnreplacedy = false;
}
}
else if (Char.IsLetter(_lookAheadCharacter))
{
// enreplacedy is written as a string
string enreplacedy = "";
// maximum length of string enreplacedies is 10 characters
for (int i = 0; i < 10 && (Char.IsLetter(_lookAheadCharacter) || Char.IsDigit(_lookAheadCharacter)); i++)
{
enreplacedy += _lookAheadCharacter;
this.ReadLookAheadCharacter();
}
if (_lookAheadCharacter == ';')
{
// advance
this.ReadLookAheadCharacter();
if (HtmlSchema.IsEnreplacedy(enreplacedy))
{
_nextCharacter = HtmlSchema.EnreplacedyCharacterValue(enreplacedy);
_nextCharacterCode = (int)_nextCharacter;
_isNextCharacterEnreplacedy = true;
}
else
{
// just skip the whole thing - invalid enreplacedy
// move on to the next character
_nextCharacter = _lookAheadCharacter;
_nextCharacterCode = _lookAheadCharacterCode;
this.ReadLookAheadCharacter();
// not an enreplacedy
_isNextCharacterEnreplacedy = false;
}
}
else
{
// skip whatever we read after the ampersand
// set next character and move on
_nextCharacter = _lookAheadCharacter;
this.ReadLookAheadCharacter();
_isNextCharacterEnreplacedy = false;
}
}
}
}
19
View Source File : HtmlLexicalAnalyzer.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
private static bool IsGoodForNameStart(char character)
{
return character == '_' || Char.IsLetter(character);
}
19
View Source File : HtmlCssParser.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
private static string ParseCssColor(string styleValue, ref int nextIndex)
{
// Implement color parsing
// rgb(100%,53.5%,10%)
// rgb(255,91,26)
// #FF5B1A
// black | silver | gray | ... | aqua
// transparent - for background-color
ParseWhiteSpace(styleValue, ref nextIndex);
string color = null;
if (nextIndex < styleValue.Length)
{
int startIndex = nextIndex;
char character = styleValue[nextIndex];
if (character == '#')
{
nextIndex++;
while (nextIndex < styleValue.Length)
{
character = Char.ToUpper(styleValue[nextIndex], CultureInfo.InvariantCulture);
if (!('0' <= character && character <= '9' || 'A' <= character && character <= 'F'))
{
break;
}
nextIndex++;
}
if (nextIndex > startIndex + 1)
{
color = styleValue.Substring(startIndex, nextIndex - startIndex);
}
}
else if (styleValue.Substring(nextIndex, 3).ToLower(CultureInfo.InvariantCulture) == "rbg")
{
// Implement real rgb() color parsing
while (nextIndex < styleValue.Length && styleValue[nextIndex] != ')')
{
nextIndex++;
}
if (nextIndex < styleValue.Length)
{
nextIndex++; // to skip ')'
}
color = "gray"; // return bogus color
}
else if (Char.IsLetter(character))
{
color = ParseWordEnumeration(_colors, styleValue, ref nextIndex);
if (color == null)
{
color = ParseWordEnumeration(_systemColors, styleValue, ref nextIndex);
if (color != null)
{
// Implement smarter system color converions into real colors
color = "black";
}
}
}
}
return color;
}
19
View Source File : Scanner.cs
License : Apache License 2.0
Project Creator : alaatm
License : Apache License 2.0
Project Creator : alaatm
private void ScanToken()
{
var c = Advance();
switch (c)
{
case '(':
AddToken(TokenType.OpenParenthesis);
break;
case ')':
AddToken(TokenType.CloseParenthesis);
break;
case '=':
AddToken(TokenType.Equal);
break;
case '!':
if (Match('='))
{
AddToken(TokenType.NotEqual);
}
else
{
throw new QueryEngineException($"Unexpected character at position '{_current}'.");
}
break;
case '\'':
ReadString();
break;
case ' ':
case '\t':
case '\r':
case '\n':
break;
default:
if (char.IsDigit(c))
{
ReadNumber();
}
else if (char.IsLetter(c))
{
ReadIdentifier();
}
else
{
throw new QueryEngineException($"Unexpected character at position '{_current}'.");
}
break;
}
}
19
View Source File : Scanner.cs
License : Apache License 2.0
Project Creator : alaatm
License : Apache License 2.0
Project Creator : 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
View Source File : NewSecurityUi.xaml.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void SearchSecurity(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
_startSearch = DateTime.Now;
_searchString = "";
LabelSearchString.Content = "";
return;
}
if (!char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
return;
}
int freshnessTime = 3; // seconds
if (_startSearch == null || DateTime.Now.Subtract(_startSearch).Seconds > freshnessTime)
{
_startSearch = DateTime.Now;
_searchString = e.KeyChar.ToString();
RefreshSearchLabel(freshnessTime);
}
else
{
_searchString += e.KeyChar.ToString();
RefreshSearchLabel(freshnessTime);
}
char[] charsToTrim = { '*', ' ', '\'', '\"', '+', '=', '-', '!', '#', '%', '.', ',' };
for (int c = 0; c < _grid.Columns.Count; c++)
{
for (int r = 0; r < _grid.Rows.Count; r++)
{
if (_grid.Rows[r].Cells[c].Value.ToString().Trim(charsToTrim)
.StartsWith(_searchString, true, CultureInfo.InvariantCulture))
{
_grid.Rows[r].Cells[c].Selected = true;
return; // stop looping
}
}
}
}
19
View Source File : AppUserService.cs
License : MIT License
Project Creator : alexyakunin
License : MIT License
Project Creator : 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
View Source File : UserNameService.cs
License : MIT License
Project Creator : alexyakunin
License : MIT License
Project Creator : alexyakunin
public ValidationException? ValidateName(string name)
{
if (string.IsNullOrEmpty(name))
return new ValidationException("Name is empty.");
if (name.Length < 4)
return new ValidationException("Name is too short.");
if (!char.IsLetter(name[0]))
return new ValidationException("Name must start with a letter.");
foreach (var c in name.replacedpan(1)) {
if (!(char.IsLetterOrDigit(c) || c == '_' || c == '-'))
return new ValidationException("Name may contain only letters, digits, '-' and '_'.");
}
return null;
}
19
View Source File : UserNameService.cs
License : MIT License
Project Creator : alexyakunin
License : MIT License
Project Creator : 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
View Source File : Lexer.cs
License : MIT License
Project Creator : alirezanet
License : MIT License
Project Creator : 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
View Source File : Lexer.cs
License : MIT License
Project Creator : Alprog
License : MIT License
Project Creator : 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
View Source File : CharExtension.cs
License : MIT License
Project Creator : AlphaYu
License : MIT License
Project Creator : AlphaYu
public static bool IsLetter(this char c)
{
return char.IsLetter(c);
}
19
View Source File : CsharpFromJsonExampleFactory.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 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
View Source File : QueryLexicalAnalizer.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
protected Token GetNextTokenFromStream()
{
SkipSpaces();
int simbol = Peek();
if (simbol == -1)
return null;
String value;
TokenType tokenType = IsSymbol(simbol);
if (tokenType != TokenType.UNKNOW)
{
value = _string.Substring(index, simbolWidth);
Skip(simbolWidth);
return new Token(tokenType, value);
}
if (simbol == '\'')
{
value = ReadString();
return new Token(TokenType.STRING, value);
}
else if (char.IsDigit((char)simbol))
{
value = ReadInteger();
simbol = Peek();
if (simbol == -1 || IsWhiteSpace(simbol))
return new Token(TokenType.INT, value);
TokenType token = IsSymbol(simbol);
if (token == TokenType.DOT)
{
Read();
return new Token(TokenType.DOUBLE, value + "." + ReadInteger());
}
else if (token != TokenType.UNKNOW)
{
return new Token(TokenType.INT, value);
}
else
throw new TokenMismatchException(String.Format("expecting number at COL: {0} ROW: {1}", Col, Row));
}
else if (simbol == '_' || Char.IsLetter((char)simbol))
{
value = ReadWord(simbol);
TokenType keyword = GetKeyword(value);
if (keyword != TokenType.UNKNOW)
{
return new Token(keyword, value);
}
return new Token(TokenType.ID, value);
}
return null;
}
19
View Source File : Proper.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
{
ValidateArguments(arguments, 1);
var text = ArgToString(arguments, 0).ToLower(CultureInfo.InvariantCulture);
var sb = new StringBuilder();
var previousChar = '.';
foreach (var ch in text)
{
if (!char.IsLetter(previousChar))
{
sb.Append(Utils.ConvertUtil._invariantTextInfo.ToUpper(ch.ToString()));
}
else
{
sb.Append(ch);
}
previousChar = ch;
}
return CreateResult(sb.ToString(), DataType.String);
}
19
View Source File : ExcelTableCollection.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
private void ValidateTableName(string Name)
{
if (string.IsNullOrEmpty(Name))
{
throw new ArgumentException("Tablename is null or empty");
}
char firstLetterOfName = Name[0];
if (Char.IsLetter(firstLetterOfName) == false && firstLetterOfName != '_' && firstLetterOfName != '\\')
{
throw new ArgumentException("Tablename start with invalid character");
}
if (Name.Contains(" "))
{
throw new ArgumentException("Tablename has spaces");
}
}
19
View Source File : Lexer.cs
License : GNU General Public License v2.0
Project Creator : Asixa
License : GNU General Public License v2.0
Project Creator : 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
View Source File : RaidProtectionModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal
License : GNU Affero General Public License v3.0
Project Creator : asmejkal
private bool MatchBlacklist(string message, IEnumerable<string> blacklist)
{
// TODO: inefficient
return blacklist.Any(x =>
{
var phrase = x.Trim('*', 1);
var i = message.IndexOf(phrase, StringComparison.OrdinalIgnoreCase);
if (i == -1)
return false;
if (i > 0 && char.IsLetter(message[i - 1]) && x.First() != '*')
return false; // Inside a word (prefixed) - skip
if (i + phrase.Length < message.Length && char.IsLetter(message[i + phrase.Length]) && x.Last() != '*')
return false; // Inside a word (suffixed) - skip
return true;
});
}
19
View Source File : Minifier.cs
License : Apache License 2.0
Project Creator : atifaziz
License : Apache License 2.0
Project Creator : atifaziz
public static IEnumerable<TResult>
Minify<TResult>(string source,
TResult space, TResult newLine,
MinificationOptions options,
Func<Token, TResult> resultSelector)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));
return _(); IEnumerable<TResult> _()
{
static bool IsSpaceOrTab (char ch) => ch is ' ' or '\t';
static bool IsAsciiLetter(char ch) => (ch & ~0x20) is >= 'A' and <= 'z';
static bool IsWordChar (char ch) => char.IsLetter(ch)
|| ch is (>= '0' and <= '9') or '_';
var lcs = LeadCommentState.Awaiting;
var lastCh = (char?)null;
var lastSingleLineCommentLine = (int?)null;
TResult NewLineWhileResettingLastChar()
{
lastCh = null;
return newLine;
}
foreach (var t in Scanner.Scan(source))
{
switch (t.Kind)
{
case TokenKind.NewLine:
case TokenKind.WhiteSpace:
break;
case var k
when k.HasTraits(TokenKindTraits.Comment)
&& options.KeepLeadComment
&& lcs != LeadCommentState.Processed
&& ( lastSingleLineCommentLine is null
|| lastSingleLineCommentLine is {} ln
&& t.Start.Line - ln == 1):
{
yield return resultSelector(t);
if (k == TokenKind.SingleLineComment)
{
lastSingleLineCommentLine = t.Start.Line;
yield return NewLineWhileResettingLastChar();
lcs = LeadCommentState.Processing;
}
else
{
lcs = LeadCommentState.Processed;
}
break;
}
case var k
when k.HasTraits(TokenKindTraits.Comment)
&& options.ShouldFilterComment(t, source):
{
yield return resultSelector(t);
if (k == TokenKind.SingleLineComment)
yield return NewLineWhileResettingLastChar();
break;
}
case var k when k.HasTraits(TokenKindTraits.Comment):
continue;
default:
{
lcs = LeadCommentState.Processed;
if (t.Kind == TokenKind.PreprocessorDirective)
{
var tei = t.End.Offset;
var si = t.Start.Offset + 1;
while (si < tei && IsSpaceOrTab(source[si]))
si++;
var ei = si;
while (ei < tei && IsAsciiLetter(source[ei]))
ei++;
var length = ei - si;
if (length == 0
|| string.CompareOrdinal("region", 0, source, si, length) != 0
&& string.CompareOrdinal("endregion", 0, source, si, length) != 0)
{
if (lastCh != null)
yield return newLine;
yield return resultSelector(t);
yield return NewLineWhileResettingLastChar();
}
}
else
{
if (lastCh is {} lch)
{
var ch = source[t.Start.Offset];
if (IsWordChar(ch) && IsWordChar(lch) || ch == lch && (ch == '+' || ch == '-' || ch == '*'))
yield return space;
}
yield return resultSelector(t);
lastCh = source[t.End.Offset - 1];
}
break;
}
}
}
}
19
View Source File : Tokeniser.cs
License : MIT License
Project Creator : atifaziz
License : MIT License
Project Creator : atifaziz
State NextStateInDirective () {
for (; position < content.Length; position++) {
char c = content[position];
if (c == '\r') {
if (position + 1 < content.Length && content[position + 1] == '\n')
position++;
nextStateLocation = nextStateLocation.AddLine();
} else if (c == '\n') {
nextStateLocation = nextStateLocation.AddLine();
} else if (Char.IsLetter (c)) {
return State.DirectiveName;
} else if (c == '=') {
nextStateLocation = nextStateLocation.AddCol ();
position++;
return State.DirectiveValue;
} else if (c == '#' && position + 1 < content.Length && content[position+1] == '>') {
position+=2;
TagEndLocation = nextStateLocation.AddCols (2);
nextStateLocation = nextStateLocation.AddCols (3);
//skip newlines directly after directives
if ((position += IsNewLine()) > 0) {
nextStateLocation = nextStateLocation.AddLine();
}
return State.Content;
} else if (!Char.IsWhiteSpace (c)) {
throw new ParserException ("Directive ended unexpectedly with character '" + c + "'", nextStateLocation);
} else {
nextStateLocation = nextStateLocation.AddCol ();
}
}
throw new ParserException ("Unexpected end of file.", nextStateLocation);
}
19
View Source File : Compiler.cs
License : GNU General Public License v3.0
Project Creator : AtomCrafty
License : GNU General Public License v3.0
Project Creator : AtomCrafty
string NextIdentifier(BinaryReader br) {
StringBuilder sb = new StringBuilder();
int ch = br.PeekChar();
if(ch == '_' || ch == '$' || char.IsLetter((char)ch)) {
do {
sb.Append((char)ch);
br.ReadChar();
ch = br.PeekChar();
}
while(ch == '_' || ch == '$' || char.IsLetter((char)ch) || char.IsDigit((char)ch));
}
return sb.ToString();
}
19
View Source File : StringConversion.cs
License : MIT License
Project Creator : Avanade
License : MIT License
Project Creator : Avanade
public static bool IsVowel(char c) => char.IsLetter(c) && (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
19
View Source File : AyExpression.cs
License : MIT License
Project Creator : ay2015
License : MIT License
Project Creator : 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
View Source File : JsonDocumentPath.cs
License : MIT License
Project Creator : azambrano
License : MIT License
Project Creator : azambrano
private string ReadRegexString()
{
StringBuilder sb = new StringBuilder();
sb.Append("\\/");
_currentIndex++;
while (_currentIndex < _expression.Length)
{
char currentChar = _expression[_currentIndex];
// handle escaped / character
if (currentChar == '\\' && _currentIndex + 1 < _expression.Length)
{
_currentIndex++;
sb.Append(currentChar);
sb.Append('\\');//duplicate
//if the next char is '/' skip it.
if (_currentIndex < _expression.Length)
{
currentChar = _expression[_currentIndex];
if (currentChar == '/')
{
_currentIndex++;
sb.Append(currentChar);
}
}
}
else if (currentChar == '/')
{
_currentIndex++;
while (_currentIndex < _expression.Length)
{
currentChar = _expression[_currentIndex];
if (char.IsLetter(currentChar))
{
if (_expression[_currentIndex - 1] == '/')
{
sb.Append("\\/");
}
_currentIndex++;
sb.Append(currentChar);
}
else
{
if (_expression[_currentIndex - 1] == '/')
{
sb.Append("\\/");
}
break;
}
}
return sb.ToString();
}
else
{
_currentIndex++;
sb.Append(currentChar);
}
}
throw new JsonException("Path ended with an open regex.");
}
19
View Source File : CSIdentifiers.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
public static bool ValidateChar(char c)
=> Char.IsLetter(c) || (c == '_');
19
View Source File : JsonIdentifiers.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : azist
public static bool ValidateChar(char c) => char.IsLetter(c) || (c == '_');
19
View Source File : Sources.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : 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
View Source File : CoreUtils.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : 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
View Source File : WebUtils.cs
License : MIT License
Project Creator : azist
License : MIT License
Project Creator : 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
View Source File : Lexer.cs
License : Apache License 2.0
Project Creator : azizamari
License : Apache License 2.0
Project Creator : azizamari
public SyntaxToken Lex()
{
//numeric
//operators
//<ws>
_start = _position;
_kind = SyntaxKind.BadToken;
_value = null;
switch (Current)
{
case '\0':
_kind=SyntaxKind.EndOfFileToken;
break;
case '+':
_kind = SyntaxKind.PlusToken;
_position++;
break;
case '-':
_kind = SyntaxKind.MinusToken;
_position++;
break;
case '%':
_kind = SyntaxKind.ModuloToken;
_position++;
break;
case '(':
_kind = SyntaxKind.OpenParenthesisToken;
_position++;
break;
case ')':
_kind = SyntaxKind.ClosedParenthesisToken;
_position++;
break;
case '[':
_kind = SyntaxKind.OpenBracketToken;
_position++;
break;
case ']':
_kind = SyntaxKind.ClosedBracketToken;
_position++;
break;
case '{':
_kind = SyntaxKind.OpenBraceToken;
_position++;
break;
case '}':
_kind = SyntaxKind.ClosedBraceToken;
_position++;
break;
case '~':
_kind = SyntaxKind.TildeToken;
_position++;
break;
case '^':
_kind = SyntaxKind.HatToken;
_position++;
break;
case ',':
_kind = SyntaxKind.CommaToken;
_position++;
break;
case ':':
_kind = SyntaxKind.ColonToken;
_position++;
break;
case '/':
_position++;
if (Current != '/')
{
_kind = SyntaxKind.SlashToken;
}
else
{
_kind = SyntaxKind.SlashSlashToken;
_position++;
}
break;
case '*':
_position++;
if (Current != '*')
{
_kind = SyntaxKind.StarToken;
}
else
{
_kind = SyntaxKind.StarStarToken;
_position++;
}
break;
case '&':
_position++;
if (Current != '&')
{
_kind = SyntaxKind.AmpersandToken;
}
else
{
_kind = SyntaxKind.AmpersandAmpersandToken;
_position++;
}
break;
case '|':
_position++;
if (Current != '|')
{
_kind = SyntaxKind.PipeToken;
}
else
{
_kind = SyntaxKind.PipePipeToken;
_position++;
}
break;
case '=':
_position++;
if (Current != '=')
{
_kind = SyntaxKind.EqualsToken;
}
else
{
_kind = SyntaxKind.EqualsEqualsToken;
_position++;
}
break;
case '!':
_position++;
if (Current != '=')
{
_kind = SyntaxKind.BangToken;
}
else
{
_kind = SyntaxKind.BangEqualsToken;
_position++;
}
break;
case '>':
_position++;
if (Current != '=')
{
_kind = SyntaxKind.GreaterToken;
}
else
{
_kind = SyntaxKind.GreaterOrEqualsToken;
_position++;
}
break;
case '<':
_position++;
if (Current != '=')
{
_kind = SyntaxKind.LessToken;
}
else
{
_kind = SyntaxKind.LessOrEqualsToken;
_position++;
}
break;
case '"':
ReadString();
break;
case '0': case '1':case '2':case '3':case '4':
case '5': case '6':case '7':case '8':case '9':
ReadNumberToken();
break;
case ' ':
case '\t':
case '\r':
case '\n':
ReadWhiteSpace();
break;
default:
if (char.IsLetter(Current))
{
ReadIdentifierOrKeyword();
}
else if (char.IsWhiteSpace(Current))
{
ReadWhiteSpace();
}
else
{
var span = new TextSpan(_position, 1);
var location = new TextLocation(_text, span);
_diagnostics.ReportBadCharacter(location,Current);
_position += 1;
}
break;
}
var length = _position - _start;
var text = _text.ToString(_start,length);
if (text == null)
{
text = _text.ToString(_start, length);
}
return new SyntaxToken(_syntaxTree, _kind, _start, text, _value);
}
19
View Source File : Lexer.cs
License : Apache License 2.0
Project Creator : azizamari
License : Apache License 2.0
Project Creator : azizamari
private void ReadIdentifierOrKeyword()
{
while (char.IsLetter(Current) ||( char.IsNumber(Current)&&_position>_start))
_position++;
var length = _position - _start;
var text = _text.ToString(_start, length);
_kind = SyntaxFacts.GetKeywordKind(text);
}
19
View Source File : GenericLexer.cs
License : MIT License
Project Creator : b3b00
License : MIT License
Project Creator : b3b00
public void AddSugarLexem(IN token, BuildResult<ILexer<IN>> buildResult, string specialValue, bool isLineEnding = false)
{
if (char.IsLetter(specialValue[0]))
{
buildResult.AddError(new InitializationError(ErrorLevel.FATAL,
I18N.Instance.GetText(I18n,Message.SugarTokenCannotStartWithLetter,specialValue,token.ToString()),
ErrorCodes.LEXER_SUGAR_TOKEN_CANNOT_START_WITH_LETTER));
return;
}
NodeCallback<GenericToken> callback = match =>
{
match.Properties[DerivedToken] = token;
return match;
};
FSMBuilder.GoTo(start);
for (var i = 0; i < specialValue.Length; i++) FSMBuilder.SafeTransition(specialValue[i]);
FSMBuilder.End(GenericToken.SugarToken, isLineEnding)
.CallBack(callback);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : badamczewski
License : MIT License
Project Creator : badamczewski
static void Colorize(char keyChar)
{
if (Definitions.OperatorGlyphs.Contains(keyChar))
{
Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop);
XConsole.Write(keyChar.ToString(), Colors.Red);
}
else if (char.IsLetter(keyChar))
{
XConsole.Write(keyChar.ToString(), Colors.Yellow);
}
else
{
XConsole.Write(keyChar.ToString(), Colors.Green);
}
}
19
View Source File : StringExtensions.cs
License : The Unlicense
Project Creator : BAndysc
License : The Unlicense
Project Creator : BAndysc
public static string ToreplacedleCase(this string str)
{
StringBuilder sb = new();
bool previousWreplacedeparator = true;
bool previousWasLetter = false;
bool previousWasLowerLetter = false;
bool previousWasDigit = false;
foreach (var c in str)
{
char chr = c;
if (chr == '_')
chr = ' ';
if (Char.IsDigit(c) && previousWasLetter)
sb.Append(' ');
if (Char.IsUpper(c) && previousWasLowerLetter)
sb.Append(' ');
if (previousWreplacedeparator)
{
sb.Append(char.ToUpper(chr));
previousWreplacedeparator = false;
}
else
sb.Append(chr);
if (chr == ' ')
previousWreplacedeparator = true;
previousWasDigit = Char.IsDigit(c);
previousWasLetter = Char.IsLetter(c);
previousWasLowerLetter = previousWasLetter && Char.IsLower(c);
}
return sb.ToString();
}
19
View Source File : PacketDocumentView.axaml.cs
License : The Unlicense
Project Creator : BAndysc
License : The Unlicense
Project Creator : BAndysc
private string GetLastWord(int offset)
{
StringBuilder sb = new();
while (offset >= 0)
{
char c = editor.Doreplacedent.GetCharAt(offset);
if (char.IsLetter(c))
sb.Insert(0, c);
else
break;
offset--;
}
return sb.ToString();
}
19
View Source File : StringExtensions.cs
License : The Unlicense
Project Creator : BAndysc
License : The Unlicense
Project Creator : BAndysc
public static string ToEnumName(this string str)
{
var sb = new StringBuilder();
foreach (var c in str)
{
if (char.IsLetter(c) || char.IsDigit(c))
sb.Append(char.ToUpperInvariant(c));
else if (c == ' ')
sb.Append('_');
}
return sb.ToString();
}
19
View Source File : DatabaseGenerator.cs
License : MIT License
Project Creator : benaadams
License : MIT License
Project Creator : benaadams
private static string SanitizeIdentifier(string symbolName)
{
if (string.IsNullOrWhiteSpace(symbolName)) return string.Empty;
var sb = new StringBuilder(symbolName.Length);
if (!char.IsLetter(symbolName[0]))
{
// Must start with a letter or an underscore
sb.Append('_');
}
var capitalize = true;
foreach (var ch in symbolName)
{
if (!char.IsLetterOrDigit(ch))
{
capitalize = true;
continue;
}
sb.Append(capitalize ? char.ToUpper(ch) : ch);
capitalize = false;
}
return sb.ToString();
}
19
View Source File : Constant.cs
License : MIT License
Project Creator : Big-Endian-32
License : MIT License
Project Creator : Big-Endian-32
public bool IsIdentifier()
{
if (!IsString())
return false;
if (reservedWords.Contains(_string))
return false;
if (_string.Length == 0)
return false;
char start = _string[0];
if (start != '_' && !char.IsLetter(start))
return false;
for (int i = 1; i < _string.Length; i++)
{
char next = _string[i];
if (char.IsLetterOrDigit(next))
continue;
if (next == '_')
continue;
return false;
}
return true;
}
See More Examples