Pattern matching for string - c#

I need a help for pattern for float value.
String that i have:
[[-307.,16.01,-171.31],[0.84528,-0.503623,-0.142485,-0.107531],[-1,-2,1,1],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]], [[-306.43,24.47,-176],[0.845282,-0.503624,-0.142472,-0.107528],[-1,-2,1,1],[9E+09,9E+09,9E+09,9E+09,9E+09,9E+09]]
Pattern that I'm using:
\s*[-+]?([0-9]*\.)?[0-9]*([eE][-+]?[0-9]+)?\s*
What changes that I have to do in my pattern such that I'm able to recognise whole text. Right now problem with
[306.43,24.47,-176] this which is part of this long string.
what changes I have to do with this pattern.

No need for regex. You can use JavaScriptSerializer
var list = new JavaScriptSerializer()
.Deserialize<List<List<List<Double>>>>("[" + yourstr + "]");

It seems you are missing a + or * for the decimal places:
\s*[-+]?([0-9].)?[0-9]+([eE][-+]?[0-9]+)?\s*

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());

C# variable in an xpath selector

Can I pass a C# string variable into an xpath selector? This is for a selenium unit test. I want to do something like this:
string myText = "foo";
Assert.IsTrue(Browser.IsElementPresent("//option[contains(text(), $myText)]"));
Using a string.Format should work:
Assert.IsTrue(Browser.IsElementPresent(string.Format("//option[contains(text(), {0}]",myText)));
yes you can use String.Format
string myText = "foo";
Assert.IsTrue(Browser.IsElementPresent(String.Format("//option[contains(text(), {0})]", myText)));
I see this has already been answered but you could also just do:
Assert.IsTrue(Browser.IsElementPresent(String.Format("//option[contains(text(), " + myText + ")]")));
This works because C# will just append each string to the end of the other.
Thank you for your answers! I was doing a Find in a table, and the above solutions did not work for me, possibly because my string contained hyphens, a decimal point, and numerals like so: "TV-8888-ZIP-54-EN-CTR.05021031"
I assigned the string to the C# variable ID. The answers above failed, I suspect, due to the decimal point and numerals. Using Nashibukasan's answer, I had to explicitly add single quotes. The working Find statement--that gets the value in the third column of the table from the same row that contains the ID string in the first column--ended up looking like this:
value = driver.FindElement(By.XPath(string.Format("//td[contains(text()," + "'" + ID + "'" + ")]/following-sibling::td[2]"))).Text;

How to Use substring in c#?

I have -$2.00 as the string. I am trying to change it to decimal by removing - and $ using substring, but I am doing it wrong. Can someone help me?
Thanks.
string m = "-$2.00";
decimal d = Math.Abs(Decimal.Parse(m, NumberStyles.Currency));
Substring will return a new string. I suspect your issue is likely from trying to mutate the string in place, which does not work.
You can do:
string result = original.Substring(2);
decimal value = decimal.Parse(result);
Depending on how the input string is generated, you may want to use decimal.TryParse instead, or some other routine with better error handling.
Don't.
Instead, you should make .Net do the dirty work for you:
Decimal value = Decimal.Parse("-$2.00", NumberStyles.Currency);
If, for some reason, you don't want a negative number, call Math.Abs.
All string operations return a new string, because string is immutable
I wouldn't use substring if you can avoid it. It would be much simpler to do something like:
string result = original.Replace("$", "").Replace("-", "");

Auto-Generate place holder format string for String.Format()

Is there a way to tell the String.Format() function (without writing my own function) how many placeholders there are dynamically? It we be great to say 15, and know I'd have {0}-{14} generated for me. I'm generate text files and I often have more than 25 columns. It would greatly help.
OK,
I will rephrase my question. I wanted to know if it is at all possible to tell the String.Format function at execution time how many place-holders I want in my format string without typing them all out by hand.
I'm guessing by the responses so far, I will just go ahead and write my own method.
Thanks!
You could use Enumerable.Range and LINQ to generate your message string.
Enumerable.Range(0, 7).Select(i => "{" + i + "}").ToArray()
generates following string:
"{0}{1}{2}{3}{4}{5}{6}"
Adding a bit to AlbertEin's response, I don't believe String.Format can do this for you out-of-the-box. You'll need to dynamically create the format string prior to using the String.Format method, as in:
var builder = new StringBuilder();
for(var i = 0; i < n; ++i)
{
builder.AppendFormat("{0}", "{" + i + "}");
}
String.Format(builder.ToString(), ...);
This isn't exactly readable, though.
Why use string.Format when there is no formatting (atleast from what I can see in your question)? You could use simple concatenation using stringbuilder instead.
There is a way to do this directly:
Just create a custom IFormatProvider, then use this overload of string.Format.
For example, if you want to always have 12 decimal points, you can do:
CultureInfo culture = Thread.CurrentThread.CurrentCulture.Clone(); // Copy your current culture
NumberFormatInfo nfi = culture.NumberFormat;
nfi.NumberDecimalDigits = 12; // Set to 12 decimal points
string newResult = string.Format(culture, "{0}", myDouble); // Will put it in with 12 decimal points

Categories