Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hi I would like to trim a string
IWF01 - STSD Campus | 1009432 | Posted Today
I need to get this string 1009432.
Or something like this
ROS03 - Roseville, CA R-3, More... | T_R_1624621 | Posted Today
I want to get this one T_R_1624621.
How do I get that part of string only?
string s = "ROS03 - Roseville, CA R-3, More... | T_R_1624621 | Posted Today";
var strArr = s.Split('|');
string yourValue = strArr[1].Trim();
Beware, this can cause some exceptions. If you don't have right string (that can be splitted by |, or if you have string that has only one | etc...
The first thing I'd do is split the string, then I'd get the 2nd item (provided that there are enough items).
Here's a function that'll do what you need (remember that it won't raise an exception if there aren't enough items):
string GetFieldTrimmed(string input, char separator, int fieldIndex)
{
var strSplitArray = input.Split(separator);
return strSplitArray.Length >= fieldIndex + 1
? strSplitArray[fieldIndex].Trim()
: "";
}
Example usage:
var fieldVal = GetFieldTrimmed("ROS03 - Roseville, CA R-3, More... | T_R_1624621 | Posted Today", '|', 1);
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 4 years ago.
Improve this question
I am new to Regex and i want to extract a specific value from a string, i have strings like:
"20098: Blue Quest"
"95: Internal Comp"
"33: ICE"
and so on.Every string has the same pattern : Number followed by ":" followed by a space and random text. I want to get the numbers at the start for ex: "20098","95","33" etc.
i tried
Regex ex = new regex(#"[0-9]+\: [a-zA-Z]$")
This is not giving me any solution, Where am i going wrong?
(i am using c#)
This is a totally silly solution. However, i decided to benchmark an unchecked pointer version, against the other regex and int parse solutions here in the answers.
You mentioned the strings are always the same format, so i decided to see how fast we could get it.
Yehaa
public unsafe static int? FindInt(string val)
{
var result = 0;
fixed (char* p = val)
{
for (var i = 0; i < val.Length; i++)
{
if (*p == ':')return result;
result = result * 10 + *p - 48;
}
return null;
}
}
I run each test 50 times with 100,000 comparisons, and 1,000,000 respectively with both Lee Gunn's int.parse,The fourth bird version ^\d+(?=: [A-Z]) also my pointer version and ^\d+
Results
Test Framework : .NET Framework 4.7.1
Scale : 100000
Name | Time | Delta | Deviation | Cycles
----------------------------------------------------------------------------
Pointers | 2.597 ms | 0.144 ms | 0.19 | 8,836,015
Int.Parse | 17.111 ms | 1.009 ms | 2.91 | 57,167,918
Regex ^\d+ | 85.564 ms | 10.957 ms | 6.14 | 290,724,120
Regex ^\d+(?=: [A-Z]) | 98.912 ms | 1.508 ms | 7.16 | 336,716,453
Scale : 1000000
Name | Time | Delta | Deviation | Cycles
-------------------------------------------------------------------------------
Pointers | 25.968 ms | 1.150 ms | 1.15 | 88,395,856
Int.Parse | 143.382 ms | 2.536 ms | 2.62 | 487,929,382
Regex ^\d+ | 847.109 ms | 14.375 ms | 21.92 | 2,880,964,856
Regex ^\d+(?=: [A-Z]) | 950.591 ms | 6.281 ms | 20.38 | 3,235,489,411
Not surprisingly regex sucks
If they are all separate strings - you don't need to use a regex, you can simply use:
var s = "20098: Blue Quest";
var index = s.IndexOf(':');
if(index > 0){
if(int.TryParse(s.Substring(0, index), out var number))
{
// Do stuff
}
}
If they're all contained in one sting, you can loop over each line and perform the Substring. Perhaps a bit easier to read as a lot of people aren't comfortable with regular expressions.
In your regex "[0-9]+: [a-zA-Z]$ you match one or more digits followed by a colon and then a single lower or uppercase character.
That would match 20098: B and would not match the digits only.
There are better alternatives besides using a regex like as suggested, but you might match from the beginning of the string ^ one or more digits \d+ and use a positive lookahead (?= to assert that what follows is a colon, whitespace and an uppercase character [A-Z])
^\d+(?=: [A-Z])
Firstly, after colon, yoiu should use \s instead of literal space. Also, if the text after colon can include spaces, the second group should also allow /s and have a + after it.
[0-9]+\:\s[a-zA-Z\s]+$
Secondly, that entire regex will return the entire string. If you only want the first number, then the regex would be simply:
[0-9]+
You can use look-behind ?<= to find any number following ^" (where ^ is the beginning of line):
(?<=^")[0-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 is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am integrating Lua in my application. But I am getting error if I am adding any if condition in Expression
string ifCondition =" return 10 + 1";
string expression = "function f()\n" + ifCondition + " \nend";
state.DoString(expression);
var scriptFunc = state["ScriptFunc"] as LuaFunction;
var res = scriptFunc.Call();
Response.Write(res[0]);
If I run above code then it will work. now I am adding if condition then it will not work.
Here is my code
string ifCondition ="If (10 < 2) then \n return 10 + 1 \n else \n return 12 end";
string expression = "function f()\n" + ifCondition + " \nend";
state.DoString(expression);
var scriptFunc = state["ScriptFunc"] as LuaFunction;
var res = scriptFunc.Call();
Response.Write(res[0]);
How can I execute if condition dynamically?
string ifCondition ="If (10 < 2) then \n return 10 + 1 \n else \n return 12 end";
Lua keywords are all lower case. Change the If to if.
By the way, C# supports multiline strings, so you could write the above as:
string ifCondition = #"
if (10 < 2) then
return 10 + 1
else
return 12
end";
Not such a big deal here, but if your snippets get longer it'll get harder to maintain them as a single line.
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.