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 7 years ago.
Improve this question
Is there a way to split the following string (containing variables x1, x2, x3)
3x1+5x2-8x3<=9
into the following tokens
{3, 1, +5, 2, -8, 3, 9}
You can use a regular expression for that and extract only numbers with signs:
const string str = "3x1+5x2-8x3<=9";
var result = Regex.Matches(str, #"([\+\-]?[\d]+)", RegexOptions.Singleline)
.Cast<Match>().Select(x => x.Value).ToList();
Result:
[0] "3" string
[1] "1" string
[2] "+5" string
[3] "2" string
[4] "-8" string
[5] "3" string
[6] "9" string
Since the case is not as complex, I would probably solve such issue by using string.Split instead of Regex:
string str = "3x1+5x2-8x3<=9";
str = str.Replace("+", "x+").Replace("-", "x-");
string[] words = str.Split(new string[] {"x", "<=", ">=", "<", ">"}, StringSplitOptions.RemoveEmptyEntries);
The idea is to make "x" the separator apart from the inequalities. I also put "<=" and ">=" inequalities before "<" and ">". This is done to avoid "<" found before "<="
Related
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 1 year ago.
Improve this question
I need to convert one phone number (badly written) to correct format. Example: + 420 741-854()642. to +420741854642
enter image description here
I think I'd just Regex replace all non digits with nothing;
var messy = "+ 420 741-854()642";
var clean = Regex.Replace(messy, "[^+0-9]", "");
For the regex pattern [^+0-9] this means "a single character that is from, the set of: (all characters except) + or 0 to 9 so in practice this pattern matches the space , hyphen -, parentheses () etc.. And any matched character (i.e. a bad character) is replaced with nothing
If you want to do it in the style you showed in the image then you can fix it by doing this:
string number = "+ 420 741-854()642.";
char[] povolene = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+' };
for(int i = 0; i < number.Length; i++) {
if (povolene.Contains(number[i])) {
.
.
.
}
}
This is a job for RegEx (Regular Expressions) :) you could have something like this: /+?\d+/gm which will return three matches from +420741-854()642 as ['+420741', '854', '642'] which can of course then be concatenated. You could always as well replace the '+' with '00' beforehand and just concatenate matches from /\d+/gm. This just matches all digits in the string.
https://regex101.com/ is a great resource for learning RegEx.
Technically, you can filter out digits (c >= '0' && c <= '9') with a help of Linq:
using System.Linq;
...
string source = "+ 420 741-854()642.";
string result = "+" + string.Concat(source.Where(c => c >= '0' && c <= '9'));
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 have a string like this -
query = "UserId:(\"787D01FE-D108-4C83-A2E2-4B1DA3166A5C\" OR \"CCA47A4F-B4FA-405C-B34E-EC2E0B1F374C\") AND CreatedDate:[2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z] OR FirstName: Abc ";
But I want to get the result in array like this -
queries=
{
[0] UserId:(\"787D01FE-D108-4C83-A2E2-4B1DA3166A5C\" OR \"CCA47A4F-B4FA-405C-B34E-EC2E0B1F374C\")
[1] AND
[2] CreatedDate:[2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z]
[3] OR
[4] FirstName: Abc
}
Updates:
So far I had used this -
var result =
(from Match m in Regex.Matches(query , #"\[[^]]*]|\{[^}]*}|[^:]+")
select m.Value)
.ToArray();
But ended with this -
SOLUTION:
Based on the solution suggested by #NetMage I added some more variations to take care of double quotes, conditions inside parenthesis Here
UserId : ("787D01FE-D108-4C83-A2E2-4B1DA3166A5C" OR "CCA47A4F-B4FA-405C-B34E-EC2E0B1F374C") AND CreatedDate : [ 2017-06-20T06:14:11Z TO 2017-07-20T06:14:11Z ] AND (FirstName : "Abc" OR LastName : "Xyz")
Regex Expression -
(?:\w+?\s*:\s*(\(.+?\)|\".+?\"|\[.+?\]|\w+))|(?:\(\w+?\s*:\s*(\(.+?\)|\".*?\"*|\[.+?\]|\w+)\))|([A-Z]+( [A-Z]+ )?)
How does this work for you?
var pattern = #"(?:\w+? ?: ?(\(.+?\)|\[.+?\]|\w+))|([A-Z]+( [A-Z]+ )?)";
var ans = Regex.Matches(query, pattern).Cast<Match>().Select(m => m.Value).ToArray();
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 7 years ago.
Improve this question
I have the following string that is captured from the DVLA when looking up a car registration details and I need to be able to extract just the numbers from the CC.
"A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 -
PRESENT"
Given that the lentgh of the string can change, is there a way to do this with a sub-string so for example always grab the numbers from before the cc without the space that comes before it? Bare in mind too that this can sometimes be a 3 digit number or a four digit number.
This does the trick:
string input = "A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 - PRESENT";
string size;
Regex r = new Regex("(\\d*)cc", RegexOptions.IgnoreCase);
Match m = r.Match(input);
if (m.Success)
{
size = m.Groups[0];
}
It captures every number that is right before cc
If the count of the comma doesn't change you can do following:
string s = "A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 - PRESENT";
string ccString = s.Split(',').ToList().Find(x => x.EndsWith("cc")).Trim();
int cc = Int32.Parse(ccString.Substring(0, ccString.Length - 2));
You can use Regex to match a pattern withing the string - so you can return parts of the string that match the given pattern. This Regex pattern will attempt to match parts of the string that fit the following pattern:
\d{1,5} *[cC]{2}
Starts with 1 to 5 digits \d{1,5} (seems sensible for an engine cc value!)
Can then contain 0 or more spaces in between that and cc *
Ends with any combination of 2 C or c [cC]{2}
So you can then use this in the following manner:
string str = "A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 - PRESENT";
Match result = Regex.Match(str, #"\d{1,5} *[cC]{2}");
string cc = result.Value; // 1968cc
Here is another solution:
string text = "A5 S LINE BLACK EDITION PLUS TDI 190 (2 DOOR), 1968cc, 2015 - PRESENT";
string[] substrings = text.Split(',');
string numeric = new String(substrings[1].Where(Char.IsDigit).ToArray());
Console.WriteLine(numeric);
Here is a working DEMO
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 8 years ago.
Improve this question
In my code I get a string as input from the user and return to him a list of names(strings) that consist inside themselves the users input.
I wish to sort this list by the index of the input in the first name and last name, with priority to the first name. example:
User input string: Da
desired result:
"David Gal"
"American Dad"
"Adam Jones"
example explanation:
"David Gal" is first because the index of "Da" is 0 in the first name.
"America Dad" is second because "Da" is also first in the last name but last names have lesser priority than first names when the index is equal.
"Adam Jones" is last because "Da" has the lowest index appearance in his name.
Edit:
I've found the answer but I don't have enough reputation to answer myself so here it is:
listToSort.OrderBy(contact =>
contact.Name
.Split(' ')
.Select((WordInName, WordIndex) =>
(uint)WordInName.IndexOf(SearchString, StringComparison.CurrentCultureIgnoreCase) + WordIndex / ((double)WordIndex + 1)
)
.Min()
);
Assuming your list looks like this:
var input = new List<string>
{
"David Gal",
"American Dad",
"Adam Jones"
};
This will give you a sorted set:
var search = "da";
var results = input
.OrderBy(w =>
w.Split(' ')
.Select(x => x.ToLower().IndexOf(search)).Max());
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a file containing data produced by string.Format(), one per line, something like:
Class1 [ Property1 = 123, Property2 = 124 ]
Class2 [ Property4 = 'ABCD', Property5 = 1234, Property6 = 10 ]
Class1 [ Property1 = 2, Property2 = 3 ]
Class2 [ Property4 = 'DEFG', Property5 = 2222, Property6 = 19 ]
and so on...
I need to parse them back to obtain the instances of the classes.
Given that I have the original string.Format template used to produce such lines, what's the fastest way to obtain back the original values so that I can build back the instances of Class1 and Class2 (for fast here I mean in terms developer's time)?
PS: I can rely on the fact that all input strings are "well formed" according to the template.
PPS: I know that using JSON would make this simpler, but right now I can't. Moreover I know Irony too, but I'm looking for something even faster (if possible).
As long as your strings don't contain special characters, here's a start:
var str = "Class1 [ Property1 = 123, Property2 = 124 ]";
var m = Regex.Match(str, #"^(?<name>[^ ]+) \[ ((?<prop>[^ ]+) = (?<val>[^ ,]+),? )+\]$");
Console.WriteLine(m.Groups["name"].Value);
for (var i = 0; i < m.Groups["prop"].Captures.Count; i++)
{
Console.WriteLine(m.Groups["prop"].Captures[i].Value);
Console.WriteLine(m.Groups["val"].Captures[i].Value);
}
Output:
Class1
Property1
123
Property2
124
If your strings do contain special characters, you could go with even more complex regular expressions, or you need to parse your string character by character, in a state machine. The first case I cannot answer because you haven't provided exact rules what your strings can or can't contain. The second case I cannot answer because it's too complex.