Extract text with random numbers inside using C# - c#

In C#, if I have a long string that will always contains somewhere a format such as W##S##Q## where # can be any number, how can I get that sequence of W##S##Q## extracted from the string. Bare in mind that the string may have more before or after but I am only interested in that sequence.
Regards.

Wobbles comment is correct, a regular expression such as #"W\d{2}S\d{2}Q\d{2}" will do what you need. \d matches any any decimal digit and the {2} afterwards tells it to match exactly twice.
This fiddle gives an example of how you would extract the string you want from a longer string.

Wobbles is right, Regular Expressions are the best way to do it generally. For your specific example, if you know in advance that the W,S,Q portions are always going to be in the same place you could use:
string testString = "WSomethingW01S02Q03SomethingElse";
bool TheRightString = false;
string WNumString = string.Empty;
string SNumString = string.Empty;
string QNumString = string.Empty;
int StartPosition = 0;
do
{
StartPosition = testString.IndexOf('W', StartPosition);
WNumString = testString.Substring(StartPosition, 3);
SNumString = testString.Substring(StartPosition + 3, 3);
QNumString = testString.Substring(StartPosition + 6, 3);
StartPosition += 1;
if (SNumString.StartsWith("S") && QNumString.StartsWith("Q"))
TheRightString = true;
} while (TheRightString == false);
Console.WriteLine(WNumString + SNumString + QNumString);
Console.ReadKey();

Related

Trying to extract code in the middle of a String

I am trying to extract a code from a string. The string can vary in content and size but I am using Tag words to make the extraction easier. However, I am struggling to nail a particular scenario. Here is the string:
({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}
What I need to extract is the 011 part of {MP.011}. The keyword will always be "{MP." It's just the code that will change. Also the rest of the expression can change so for example {MP.011} could be at the beginning, end or middle of the string.
I've got close using the following:
int pFrom = code.IndexOf("{MP.") + "{MP.".Length;
int pTo = code.LastIndexOf("}");
String result = code.Substring(pFrom, pTo - pFrom);
However, the result is 011} + {SilverPrice as it is looking for the last occurrence of }, not the next occurrence. This is where I am struggling.
Any help would be much appreciated.
You could use a regular expression to parse that:
var str = "({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
var number = Regex.Match(str, #"{MP\.(\d+)}")
.Groups[1].Value;
Console.WriteLine(number);
int pFrom = code.IndexOf("{MP.") + "{MP.".Length;
int pTo = code.IndexOf("}", pFrom); //find index of } after start
String result = code.Substring(pFrom, pTo - pFrom);
the safest option is to use Regex with Negative and Positive Lookahead. This also matches multiple if you need it anyway.
var str3 = #"({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
var result = Regex.Matches(str3, #"(?<=\{MP\.).+?(?=\})");
foreach (Match i in result)
{
Console.WriteLine(i.Value);
}
The key is to use the .IndexOf(string text,int start) overload.
static void Main(string[] args)
{
string code = "({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
// Step 1. Extract "MP.011"
int pFrom = code.IndexOf("{MP.");
int pTo = code.IndexOf("}", pFrom+1);
string part = code.Substring(pFrom+1, pTo-pFrom-1);
// Step 2. Extact "011"
String result = part.Substring(3);
}
or you can combine the last statements into
String result = code.Substring(pFrom+1, pTo-pFrom-1).Substring(3);

ASP.Net - Masked first 6 character on a string with dynamic length

is it possible to masked a first 6 characters on a string if the string is dynamics on it's length?
Example, I have a string "test123456789" and I want a result of "******3456789" or a string of "1234test" and I want a result of "******st". All I'm seeing sample codes here in masking are strings with a static length. Can anyone kindly help me with this? Thank you so much in advance.
Yes, it's possible, and even quite easy, using simple string concatenation and SubString:
var original = "Some string here";
var target = "******" + ((original.Length > 6) ? original.Substring(6) : "") ;
If you want shorter strings to mask all characters but keep original length, you can do it like this:
var target = new string('*', Math.Min(original.Length, 6)) + ((original.Length > 6) ? original.Substring(6) : "") ;
This way, an input of "123" would return 3 asterisks ("***"). The first code I've shown will return 6 asterisks ("******")
Linq is an alternative to Substring and ternary operator solution (see Zohar Peled's answer):
using System.Linq;
...
string original = "Some string here";
string result = "******" + string.Concat(original.Skip(6));
If you want to preserve the length of short (less than 6 character string):
// if original shorter than 6 symbols, e.g. "short"
// we'll get "*****" (Length number of *, not 6)
// if original has six or more symbols, e.g. "QuiteLong"
// we'll get "******ong" as usual
string original = "short";
...
string result = new string('*', Math.Min(6, original.Length)) +
string.Concat(original.Skip(Math.Min(6, original.Length)));
You may want to have the routine as an extension method:
public static partial class StringExtensions {
public static string MaskPrefix(this string value, int count = 6) {
if (null == value)
throw new ArgumentNullException("value"); // or return value
else if (count < 0)
throw new ArgumentOutOfRangeException("count"); // or return value
int length = Math.Min(value.Length, count);
return new string('*', length) + string.Concat(value.Skip(length));
}
}
And so you can put as if string has MaskPrefix method:
string original = "Some string here";
string result = original.MaskPrefix(6);
You can substring and mask it. Make sure to check if the input string is lower than 6 as below sample
string str = "123456789345798";
var strResult = "******"+str.Substring(6, str.Length - 6);
Console.WriteLine("strResult :" + strResult);

Errors with splitting string

I'm quite new to programming and I'm trying to split the string below to just 36.20C but I keep getting ArgumentOutOfRangeWasUnhandled. why?
private void button1_Click(object sender, EventArgs e)
{
string inStr = "Temperature:36.20C";
int indexOfSpace = inStr.IndexOf(':');
//stores the address of the space
int indexOfC = inStr.IndexOf("C");
//stores the address of char C
string Temp = inStr.Substring(indexOfSpace + 1, indexOfC);
textBox1.Text = Temp;
}
expected output : 36.20C
The second argument of String.Substring is the length but you have provided the end index. You need to subtract them:
string Temp = inStr.Substring(++indexOfSpace, indexOfC - indexOfSpace);
You could also remove the C from the end:
string Temp = inStr.Substring(++indexOfSpace).TrimEnd('C'); // using the overload that takes the rest
As an aside, you should use the overload of IndexOf with the start-index in this case:
int indexOfC = inStr.IndexOf('C', indexOfSpace);
Here is an easier approach:
Temp = inStr.Split(':').Last().TrimEnd('C');
If you check the documentation for Substring, you'll see that the second parameter is the length, not the end position. However, there is an overload for SubString that only needs the start position and it'll return the string from there to the end of the string:
int indexOfSpace = inStr.IndexOf(':');
string Temp = inStr.Substring(indexOfSpace + 1);
var arrayStr = inStr.split(':');
textbox1.text = arrayStr[1];
you can do it like
string Temp = inStr.Substring(indexOfSpace + 1, inStr.Length - indexOfSpace - 1)
Second parameter of Substring is length. You must update as following:
string Temp = inStr.Substring(indexOfSpace + 1, indexOfC - indexOfSpace);
Just use string.Split().
string[] temp = inStr.Split(':');
textbox1.Text = temp[1];
// temp[1] returns "36.20C"
// temp[0] returns "Temperature"
string temperature = "temperature:32.25C";
Console.WriteLine(temp.Substring(temp.Trim().IndexOf(':')+1));
In substring, 2nd argument is length and if u do not specify any argument substring processes till the end of string.

Substring from specific sign to sign

I have a list of strings in format like this:
Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp
I need only the part from comma sign to the first dot sign.
For example above it should return this string: IScadaManualOverrideService
Anyone has an idea how can I do this and get substrings if I have list of strings like first one?
from comma sign to the first dot sign
You mean from dot to comma?
You can split the string by comma first, then split by dot and take the last:
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string result = text.Split(',')[0].Split('.').Last(); // IScadaManualOverrideService
Splitting strings is not what can be called effective solution. Sorry can't just pass nearby.
So here is another one
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', end) + 1;
var result = text.Substring(start, end - start);
Proof woof woof.
Bullet-proof version (ugly)
string text = "IScadaManualOverrideService";
//string text = "Services.IScadaManualOverrideService";
//string text = "IScadaManualOverrideService,";
//string text = "";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', (end == -1 ? text.Length - 1 : end)) + 1;
var result = text.Substring(start, (end == -1 ? text.Length : end) - start);
Insert this if hacker attack is expected
if(text == null)
return "Stupid hacker, die!";
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string s1 = s.Substring(0, s.IndexOf(","));
string s2 = s1.Substring(s1.LastIndexOf(".") + 1);
string input = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
int commaIndex = input.IndexOf(',');
string remainder = input.Substring(0, commaIndex);
int dotIndex = remainder.LastIndexOf('.');
string output = remainder.Substring(dotIndex + 1);
This can be written a lot shorter, but for the explanation i think this is more clear
sampleString.Split(new []{','})[0].Split(new []{'.'}).Last()
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string subStr = new string(s.TakeWhile(c => c != ',').ToArray());
string last = new string(subStr.Reverse().TakeWhile(c => c != '.').Reverse().ToArray());
Console.WriteLine(last); // output: IScadaManualOverrideService

Getting number from a string in C#

I am scraping some website content which is like this - "Company Stock Rs. 7100".
Now, what i want is to extract the numeric value from this string. I tried split but something or the other goes wrong with my regular expression.
Please let me know how to get this value.
Use:
var result = Regex.Match(input, #"\d+").Value;
If you want to find only number which is last "entity" in the string you should use this regex:
\d+$
If you want to match last number in the string, you can use:
\d+(?!\D*\d)
int val = int.Parse(Regex.Match(input, #"\d+", RegexOptions.RightToLeft).Value);
I always liked LINQ:
var theNumber = theString.Where(x => char.IsNumber(x));
Though Regex sounds like the native choice...
This code will return the integer at the end of the string. This will work better than the regular expressions in the case that there is a number somewhere else in the string.
public int getLastInt(string line)
{
int offset = line.Length;
for (int i = line.Length - 1; i >= 0; i--)
{
char c = line[i];
if (char.IsDigit(c))
{
offset--;
}
else
{
if (offset == line.Length)
{
// No int at the end
return -1;
}
return int.Parse(line.Substring(offset));
}
}
return int.Parse(line.Substring(offset));
}
If your number is always after the last space and your string always ends with this number, you can get it this way:
str.Substring(str.LastIndexOf(" ") + 1)
Here is my answer ....it is separating numeric from string using C#....
static void Main(string[] args)
{
String details = "XSD34AB67";
string numeric = "";
string nonnumeric = "";
char[] mychar = details.ToCharArray();
foreach (char ch in mychar)
{
if (char.IsDigit(ch))
{
numeric = numeric + ch.ToString();
}
else
{
nonnumeric = nonnumeric + ch.ToString();
}
}
int i = Convert.ToInt32(numeric);
Console.WriteLine(numeric);
Console.WriteLine(nonnumeric);
Console.ReadLine();
}
}
}
You can use \d+ to match the first occurrence of a number:
string num = Regex.Match(input, #"\d+").Value;

Categories