Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In C# I'm trying to search for the substring "flight%sin" where %s would be a string. How would I do this using regex in c#?
You can capture the text between "flight" and "in" using #"flight(\w+)in"
The reference guide provides more detail.
Here is a Regex example in C#.
string [] mystrings = new string [] {"flight%sin", "flightTest1sin", "flighNoGoodsin", "flightTest2sin"};
foreach (string s in mystrings)
{
var groups = Regex.Match(s, #"flight(\w+)in");
if (groups.Groups.Count > 1)
{
Console.WriteLine(groups.Groups[1]);
}
}
Console.ReadKey();
Does this help?
string data = "flight 4057 in"; //I am guessing, this is what the original string will be.
public string getFlightNumber(string data)
{
int flightNumLength = 4;// Or however long the string would be
for(int index = 0; index < data.length(); index++)
{
if(index+flightNumLength + index < data.length())
{
string TempFlight = data.subSting(index, flightNumLength);
if(isNumeric(TempFlight))
{
return TempFlight;
}
}
}
}
public static bool IsNumeric(object Expression){
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any,System.Globalization.NumberFormatInfo.InvariantInfo, out retNum );
return isNum;
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to take the following string as input:
first-arg second-arg "third arg with spaces" "arg with \" quotes"
and return this list of strings as output
["first-arg", "second-arg", "third arg with spaces", "arg with \" quotes"]
Are there any nuget packages or built in functions that can do this? I want it to handle edge cases like arguments containing multiple words and arguments containing quotes.
string[] arguments = Environment.GetCommandLineArgs();
For more information see the MSDN website
This class satisfies the requirements. It's not the most effective way, but it returns the right arguments.
public static class ArgumentLineParser
{
public static string[] ToArguments(string cmd)
{
if (string.IsNullOrWhiteSpace(cmd))
{
return new string[0];
}
var argList = new List<string>();
var parseStack = new Stack<char>();
bool insideLiteral = false;
for (int i = 0; i < cmd.Length; i++)
{
bool isLast = i + 1 >= cmd.Length;
if (char.IsWhiteSpace(cmd[i]) && insideLiteral)
{
// Whitespace within literal is kept
parseStack.Push(cmd[i]);
}
else if (char.IsWhiteSpace(cmd[i]))
{
// Whitespace delimits arguments
MoveArgumentToList(parseStack, argList);
}
else if (!isLast && '\\'.Equals(cmd[i]) && '"'.Equals(cmd[i + 1]))
{
//Escaped double quote
parseStack.Push(cmd[i + 1]);
i++;
}
else if ('"'.Equals(cmd[i]) && !insideLiteral)
{
// Begin literal
insideLiteral = true;
}
else if ('"'.Equals(cmd[i]) && insideLiteral)
{
// End literal
insideLiteral = false;
}
else
{
parseStack.Push(cmd[i]);
}
}
MoveArgumentToList(parseStack, argList);
return argList.ToArray();
}
private static void MoveArgumentToList(Stack<char> stack, List<string> list)
{
var arg = string.Empty;
while (stack.Count > 0)
{
arg = stack.Pop() + arg;
}
if (arg != string.Empty)
{
list.Add(arg);
}
}
}
It can be used like this:
var line = #"first-arg second-arg ""third arg with spaces"" ""arg with \"" quotes""";
var args = ArgumentLineParser.ToArguments(line);
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The method looks as following:
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
var result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
return result;
}
}
It's obvious that not all paths return something and the issue is I can't return null.
How to rearrange the method?
Maybe you can initialize your List?
private static List<string> SetPointObjectDefectRow(string[] row, string owner)
{
const int zone = 54;
const string band = "U";
List<string> result = new List<string>()
{
owner,
string.Empty,
string.Empty
};
if (Helpers.NormalizeLocalizedString(row[7]).Contains(#"a") ||
Helpers.NormalizeLocalizedString(row[12]).Contains(#"b"))
{
var geoPosition = UtmConverter.StringUtmFormatToLocation(zone, band, Convert.ToDouble(row[15]), Convert.ToDouble(row[14]));
var beginGeoPosition = geoPosition.LatString + ", " + geoPosition.LngString;
result = new List<string>
{
owner,
row[4],
beginGeoPosition
};
}
return result;
}
I usually do this when I want to create an assembler method for example to tranform a List<X> to another List<Y>, so if my List<X> is null I try to return an empty List of Y. I prefer to do this instead of throwing exceptions and getting my Dashboard full of errors. But It depends on how your codes works.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have to parse this string
"Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing"
as Code, Description like Code=Cust and Description=Customer
split on basis of space is not working for this because there is also a space in description too .
Instead of splitting on space you can split on the equals sign. Then the code will be the value after the last space of the previous item and the description will be everything up to the last space making sure to trim the spaces that might show up before the equals. And you can replace the Dictionary with whatever data type you want to load the values into. Also you have to handle the first and last values as special cases. Note this will only work if the codes do not contain spaces.
string str = "Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing";
var separated = str.Split('=');
string code = separated[0].Trim();
var codeAndDescription = new Dictionary<string, string>();
for (int i = 1; i < separated.Length - 1; i++)
{
int lastSpace = separated[i].Trim().LastIndexOf(' ');
var description = separated[i].Substring(0, lastSpace).Trim();
codeAndDescription.Add(code, description);
code = separated[i].Substring(lastSpace + 1).Trim();
}
codeAndDescription.Add(code, separated[separated.Length - 1]);
foreach (var kvp in codeAndDescription)
Console.WriteLine(kvp);
Outputs
[Cust, Customer]
[CustCR, Customer Credit]
[Prod, Product]
[SalesRep, Sales Rep]
[TaxCat, Tax Category]
[TaxId, Tax ID]
[VolBill, Volume Billing]
A little modification for another case if description is empty, also used custom Item class to store output in a list
class Item {
public string Code { get; set; }
public string Description { get; set; }
}
class Program
{
static void Main(string[] args)
{
string str = "0= 1=Full Time 2=Part Time 3=Seasonal 4=Variable";
var separated = str.Split('=');
string code = separated[0].Trim();
var codeAndDescription = new List<Item>();
foreach (var sep in separated.Skip(1).Take(separated.Length - 2))
{
int lastSpace = sep.Trim().LastIndexOf(' ');
var description = lastSpace != -1 ? sep.Substring(0, lastSpace).Trim(): "" ;
codeAndDescription.Add(new Item { Code=code,Description=description });
code = sep.Substring(lastSpace + 1).Trim();
}
codeAndDescription.Add(new Item { Code = code, Description = separated.Last() });
foreach (var kvp in codeAndDescription)
{
Console.WriteLine("Code={0} Description={1}", kvp.Code, kvp.Description);
}
Console.ReadLine();
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
By using RegEx, or String.Replace, I need to replace any number of consecutive #'s (with the appropriate number of leading 0's) with an integer. I know I can search for # in the string, get the First and Last index, Last-First for the length, then replace with String.Replace. I was hoping someone would have a faster, and more slick answer.
Method header would be:
string ReplaceHashtagsWithInt(string input, int integer)
Examples:
Input -> "String####_Hi##", 2
Output -> "String0002_Hi02"
Input -> "String####_Hi##", 123
Output -> "String0123_Hi123"
public static class Testing
{
public static void Main()
{
ReplaceHashtagsWithInt("String####_Hi##", 2);
ReplaceHashtagsWithInt("String####_Hi###", 123);
ReplaceHashtagsWithInt("String####_Hi#######", 123);
}
public static string ReplaceHashtagsWithInt(string input, int integer)
{
Regex regex = new Regex("#+");
var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value).ToArray();
Array.Sort(matches);
Array.Reverse(matches);
foreach (string match in matches)
{
Regex r = new Regex(match);
string zeroes = new string('0', match.Length - integer.ToString().Length) + integer;
input = r.Replace(input, zeroes);
}
return input;
}
}
You can do something like this:
using System;
using System.Text;
using System.Text.RegularExpressions;
public static class Testing
{
public static void Main()
{
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 1));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 23));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 456));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 7890));
Console.WriteLine(ReplaceHashtagsWithInt("###_####_#", 78901));
}
public static string ReplaceHashtagsWithInt(string input, int integer)
{
Regex regex = new Regex("#+");
StringBuilder output = new StringBuilder(input);
int allig = 0;
for(Match match = regex.Match(input);match.Success;match = match.NextMatch())
{
string num = integer.ToString();
if(num.Length<=match.Length)
for(int i=0;i<match.Length;i++)
{
if(i<match.Length-num.Length)
output[match.Index+i+allig] = '0';
else
output[match.Index+i+allig] = num[i-match.Length+num.Length];
}
else
{
output.Remove(match.Index+allig,match.Length);
output.Insert(match.Index+allig,num);
allig+=num.Length-match.Length;
}
}
return output.ToString();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to extract the PropertyInfo of an object but the propertyInfo returns no properties:
[TestMethod]
public void TestGetValueMethod()
{
var value = 23;
System.Reflection.PropertyInfo[] propertyInfo = value.GetType ().GetProperties();
//DTOPropertyInfo info = new DTOPropertyInfo(propertyInfo[0]);
System.Diagnostics.Debug.WriteLine(propertyInfo.Length);
}
propertyInfo.Length returns 0. What am I missing?
using System;
using System.Reflection;
class Example
{
public static void Main()
{
string test = "abcdefghijklmnopqrstuvwxyz";
// Get a PropertyInfo object representing the Chars property.
PropertyInfo pinfo = typeof(string).GetProperty("Chars");
// Show the first, seventh, and last letters
ShowIndividualCharacters(pinfo, test, 0, 6, test.Length - 1);
// Show the complete string.
Console.Write("The entire string: ");
for (int x = 0; x < test.Length; x++)
{
Console.Write(pinfo.GetValue(test, new Object[] {x}));
}
Console.WriteLine();
}
static void ShowIndividualCharacters(PropertyInfo pinfo,
object value,
params int[] indexes)
{
foreach (var index in indexes)
Console.WriteLine("Character in position {0,2}: '{1}'",
index, pinfo.GetValue(value, new object[] { index }));
Console.WriteLine();
}
}