How to remove word from the string in a generic way - c#

I have a string which is basically a url something like APIPAth/resources/customers/SSNNumber/authorizations/contracts.
The SSNNumber can be of any value. Its the actual SSN number which I want to remove from the string and the string should look like APIPAth/resources/customers/authorizations/contracts.
I can't find a proper solution in which without hardcoding the word and removing the string
I tried using Find and Replace but I think the function would require the particular word

Looking at the URL you provided, it appears you only want to get rid of digits. You could accomplish that with this line:
var output = Regex.Replace(input, #"[\d]", string.Empty);

There are many ways to skin this cat depending on what stays static.
One way would be to split the url by separators and join them back
var url = #"APIPAth/resources/customers/SSNNumber/authorizations/contracts";
var items = new List<string>(url.Split('/'));
items.RemoveAt(3);
url = string.Join("/", items);
Another way would be to use Regex
var url = #"APIPAth/resources/customers/SSNNumber/authorizations/contracts";
url = Regex.Replace(url, #"/customers/[^/]+/authorizations/", "/customers/authorizations/")
If you elaborate on what you expect in a generic solution, i.e. what part stays static, then I can help you out better

If SSN in number then it has to have form of this 000 00 0000 means 9 digits consequents.
Took a string parse it by / and you get an array of elements lets say parsed
for(int i=0; i<parsed.length; i++){
if(parsed[i].length === 9){
...keep this i...
}
}
remove this parsed[i] from whole parsed and concat with /

Related

Split string with plus sign as a delimiter

I have an issue with a string containing the plus sign (+).
I want to split that string (or if there is some other way to solve my problem)
string ColumnPlusLevel = "+-J10+-J10+-J10+-J10+-J10";
string strpluslevel = "";
strpluslevel = ColumnPlusLevel;
string[] strpluslevel_lines = Regex.Split(strpluslevel, "+");
foreach (string line in strpluslevel_lines)
{
MessageBox.Show(line);
strpluslevel_summa = strpluslevel_summa + line;
}
MessageBox.Show(strpluslevel_summa, "summa sumarum");
The MessageBox is for my testing purpose.
Now... The ColumnPlusLevel string can have very varied entry but it is always a repeated pattern starting with the plus sign.
i.e. "+MJ+MJ+MJ" or "+PPL14.1+PPL14.1+PPL14.1" as examples.
(It comes form Another software and I cant edit the output from that software)
How can I find out what that pattern is that is being repeated?
That in this exampels is the +-J10 or +MJ or +PPL14.1
In my case above I have tested it by using only a MessageBox to show the result but I want the repeated pattering stored in a string later on.
Maybe im doing it wrong by using Split, maybe there is another solution.
Maybe I use Split in the wrong way.
Hope you understand my problem and the result I want.
Thanks for any advice.
/Tomas
How can I find out what that pattern is that is being repeated?
Maybe i didn't understand the requirement fully, but isn't it easy as:
string[] tokens = ColumnPlusLevel.Split(new[]{'+'}, StringSplitOptions.RemoveEmptyEntries);
string first = tokens[0];
bool repeatingPattern = tokens.Skip(1).All(s => s == first);
If repeatingPattern is true you know that the pattern itself is first.
Can you maybe explain how the logic works
The line which contains tokens.Skip(1) is a LINQ query, so you need to add using System.Linq at the top of your code file. Since tokens is a string[] which implements IEnumerable<string> you can use any LINQ (extension-)method. Enumerable.Skip(1) will skip the first because i have already stored that in a variable and i want to know if all others are same. Therefore i use All which returns false as soon as one item doesn't match the condition(so one string is different to the first). If all are same you know that there is a repeating pattern which is already stored in the variable first.
You should use String.Split function :
string pattern = ColumnPlusLevel.Split("+")[0];
...but it is always a repeated pattern starting with the plus sign.
Why do you even need String.Split() here if the pattern always only repeats itself?
string input = #"+MJ+MJ+MJ";
int indexOfSecondPlus = input.IndexOf('+', 1);
string pattern = input.Remove(indexOfSecondPlus, input.Length - indexOfSecondPlus);
//pattern is now "+MJ"
No need of string split, no need to use LinQ
String has a method called Split which let's you split/divide the string based on a given character/character-set:
string givenString = "+-J10+-J10+-J10+-J10+-J10"'
string SplittedString = givenString.Split("+")[0] ///Here + is the character based on which the string would be splitted and 0 is the index number
string result = SplittedString.Replace("-","") //The mothod REPLACE replaces the given string with a targeted string,i added this so that you can get the numbers only from the string

Fixed string Regular Expression C#

Hi all I want to know something regarding to fixed-string in regular expression.
How to represent a fixed-string, regardless of special characters or alphanumeric in C#?
For eg; have a look at the following string:
infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X
The entire string before X will be fixed-string (ie; the whole sentence will appear the same) BUT only X will be the decimal variable.
What I want is that I want to append decimal number X to the fixed string. How to express that in terms of C# regular expression.
Appreciate your help
string fulltext = "inifinity.world.uk/Members/namelist.aspx?ID=-1&fid=" + 10;
if you need to modify existing url, dont use regex, string.Format or string.Replace you get problem with encoding of arguments
Use Uri and HttpUtility instead:
var url = new Uri("http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X");
var query = HttpUtility.ParseQueryString(url.Query);
query["fid"] = 10.ToString();
var newUrl = url.GetLeftPart(UriPartial.Path) + "?" + query;
result: http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=10
for example, using query["fid"] = "%".ToString(); you correctly generate http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=%25
demo: https://dotnetfiddle.net/zZ9Y1h
String.Format is one way of replacing token values in a string, if that's what you want. In the example below, the {0} is a token, and String.Format takes the fixedString and replaces the token with the value of myDecimal.
string fixedString = "infinity.world.uk/Members/namelist.aspx?ID=-1&fid={0}";
decimal myDecimal = 1.5d;
string myResultString = string.Format(fixedString, myDecimal.ToString());

Regular expression for parsing CSV

I'm trying to parse a CSV file in C#. Split on commas (,). I got it to work with this:
[\t,](?=(?:[^\"]|\"[^\"]*\")*$)
Splitting this string:
2012-01-06,"Some text with, comma",,"300,00","143,52"
Gives me:
2012-01-06
"Some text with, comma"
"300,00"
"143,52"
But I can't figure out how to lose the "" from the output so I get this instead:
2012-01-06
Some text with, comma
300,00
143,52
Any suggestions?
If you are trying to parse a CSV and using .NET, don't use regular expressions. Use a component that was created for this purpose. See the question CSV File Imports in .Net.
I know the CSV specification looks simple enough, but trust me, you are in for heartache and destruction if you continue down this path.
Why are you using regular expressions for this? Ensuring the file is well-formed?
You can use String.Replace()
String s = "Some text with, comma";
s = s.Replace("\"", "");
// After matched
String line = 2012-01-06,"Some text with, comma",,"300,00","143,52";
String []fields = line.Split(',');
for (int i = 0; i < fields.Length; i++)
{
// Call a function to remove quotes
fields[i] = removeQuotes(fields[i]);
}
String removeQuotes(String s)
{
return s.Replace("\"", "");
}
So, something like this. Again, I wouldn't use RegEx for this purpose, but YMMV.
var sp = Regex.Split(a, "[\t,](?=(?:[^\"]|\"[^\"]*\")*$)")
.Select(s => Regex.Replace(s.Replace("\"\"","\""),"^\"|\"$","")).ToArray();
So, the idea here is that first of all, you want to replace double double quotes with a single double quote. And then that string is fed to the second regex which simply removes double quotes at the beginning and end of the string.
The reason for the first replace is because of strings like this:
var a = "1999,Chevy,\"Venture \"\"Extended Edition, Very Large\"\" Dude\",\"\",\"5000.00\"";
So, this would give you a string like this: ""Extended Edition"", and the double quotes need to be changed to single quotes.

C# Regex.Match to decimal

I have a string "-4.00 %" which I need to convert to a decimal so that I can declare it as a variable and use it later. The string itself is found in string[] rows. My code is as follows:
foreach (string[] row in rows)
{
string row1 = row[0].ToString();
Match rownum = Regex.Match(row1.ToString(), #"\-?\d+\.+?\d+[^%]");
string act = Convert.ToString(rownum); //wouldn't convert match to decimal
decimal actual = Convert.ToDecimal(act);
textBox1.Text = (actual.ToString());
}
This results in "Input string was not in a correct format." Any ideas?
Thanks.
I see two things happening here that could contribute.
You are treating the Regex Match as though you expect it to be a string, but what a Match retrieves is a MatchGroup.
Rather than converting rownum to a string, you need to lookat rownum.Groups[0].
Secondly, you have no parenthesised match to capture. #"(\-?\d+\.+?\d+)%" will create a capture group from the whole lot. This may not matter, I don't know how C# behaves in this circumstance exactly, but if you start stretching your regexes you will want to use bracketed capture groups so you might as well start as you want to go on.
Here's a modified version of your code that changes the regex to use a capturing group and explicitly look for a %. As a consequence, this also simplifies the parsing to decimal (no longer need an intermediary string):
EDIT : check rownum.Success as per executor's suggestion in comments
string[] rows = new [] {"abc -4.01%", "def 6.45%", "monkey" };
foreach (string row in rows)
{
//regex captures number but not %
Match rownum = Regex.Match(row.ToString(), #"(\-?\d+\.+?\d+)%");
//check for match
if(!rownum.Success) continue;
//get value of first (and only) capture
string capture = rownum.Groups[1].Value;
//convert to decimal
decimal actual = decimal.Parse(capture);
//TODO: do something with actual
}
If you're going to use the Match class to handle this, then you have to access the Match.Groups property to get the collection of matches. This class assumes that more than one occurrence appears. If you can guarantee that you'll always get 1 and only 1 you could get it with:
string act = rownum.Groups[0];
Otherwise you'll need to parse through it as in the MSDN documentation.

How to get id from String with using Regex

I want to get only number id from string. result : 123456
var text = "http://test/test.aspx?id=123456dfblablalab";
EDIT:
Sorry, Another number can be in the text. I want to get first number after id.
var text = "http://test/test.aspx?id=123456dfbl4564dsf";
Use:
Regex.Match(text, #"id=(\d+)").Groups[1].Value;
It depends on the context - in this case it looks like you are parsing a Uri and a query string:
var text = "http://test/test.aspx?id=123456dfblablalab";
Uri tempUri = new Uri(text);
NameValueCollection query = HttpUtility.ParseQueryString(tempUri.Query);
int number = int.Parse(new string(query["id"].TakeWhile(char.IsNumber).ToArray()));
Someone will give you a C# implementation, but it's along the lines of
/[\?\&]id\=([0-9]+)/
Which will match either &id=123456fkhkghkf or ?id=123456fjgjdfgj (so it'll get the value wherever it is in the URL) and capture the number as a match.

Categories