C# Regex help getting multiple values - c#

Needing a bit help getting multiple values from a string using Regex. I am fine getting single values from the string but not multiple.
I have this string:
[message:USERPIN]Message to send to the user
I need to extract both the USERPIN and the message. I know how to get the pin:
Match sendMessage = Regex.Match(message, "\\[message:[A-Z1-9]{5}\\]");
Just not sure how to get both of the values at the same time.
Thanks for any help.

Use Named Groups for easy access:
Match sendMessage = Regex.Match(message,
#"\[message:(?<userpin>[A-Z1-9]{5})\](?<message>.+)");
string pin = sendMessage.Groups["userpin"].Value;
string message = sendMessage.Groups["message"].Value;

var match = Regex.Match(message, #"\[message:([^\]]+)\](.*)");
After - inspect the match.Groups with debugger - there you have to see 2 strings that you expect.

You need to use numbered groups.
Match sendMessage = Regex.Match(message, "\\[message:([A-Z1-9]{5})(.*)\\]");
string firstMatch = sendMessage.Groups[1].Value;
string secondMatch = sendMessage.Groups[2].Value;

Related

How can I make a string out of a complex URL address

I've been trying to make this URL a workable string in C#, but unfortunately using extra "" or "#" is not cutting it. Even breaking it into smaller strings is proving difficult. I want to be able to convert the entire address into a single string.
this is the full address:
<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT="+URLEncode(""+[Material].[Material - Key])+"&lsIZV_MAT=>
I've also tried this:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"+ URLEncode("" +[Material].[Material - Key]) + """"";
string url3 = #"&lsIZV_MAT=";
Any help is appreciated.
The simplest solution is put additional quotes inside string literal and use string.Concat to join all of them into single URL string:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
string resultUrl = string.Concat(url, url2, url3);
NB: You can use Equals method or == operator to check if the generated string matches with desired URL string.
This may be a bit of a workaround rather than an actual solution but if you load the string from a text file and run to a breakpoint after it you should be able to find the way the characters are store or just run it from that.
You may also have the issue of some of the spaces you've added being left over which StringName.Replace could solve if that's causing issues.
I'd recommend first checking what exactly is being produced after the third statement and then let us know so we can try and see the difference between the result and original.
You are missing the triple quotes at the beginning of url2
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
I just made two updates
t&lsMZV_MAT=" to t&lsMZV_MAT="" AND
[Material - Key])+" to [Material - Key])+""
string s = #"<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=""+ URLEncode([Material].[Material - Key])+""&lsIZV_MAT=>";
Console.Write(s);
Console.ReadKey();

Get only numbers from line in file

So I have this file with a number that I want to use.
This line is as follows:
TimeAcquired=1433293042
I only want to use the number part, but not the part that explains what it is.
So the output is:
1433293042
I just need the numbers.
Is there any way to do this?
Follow these steps:
read the complete line
split the line at the = character using string.Split()
extract second field of the string array
convert string to integer using int.Parse() or int.TryParse()
There is a very simple way to do this and that is to call Split() on the string and take the last part. Like so if you want to keep it as a string:
var myValue = theLineString.Split('=').Last();
If you need this as an integer:
int myValue = 0;
var numberPart = theLineString.Split('=').Last();
int.TryParse(numberPart, out myValue);
string setting=sr.ReadLine();
int start = setting.IndexOf('=');
setting = setting.Substring(start + 1, setting.Length - start);
A good approach to Extract Numbers Only anywhere they are found would be to:
var MyNumbers = "TimeAcquired=1433293042".Where(x=> char.IsDigit(x)).ToArray();
var NumberString = new String(MyNumbers);
This is good when the FORMAT of the string is not known. For instance you do not know how numbers have been separated from the letters.
you can do it using split() function as given below
string theLineString="your string";
string[] collection=theLineString.Split('=');
so your string gets divided in two parts,
i.e.
1) the part before "="
2) the part after "=".
so thus you can access the part by their index.
if you want to access numeric one then simply do this
string answer=collection[1];
try
string t = "TimeAcquired=1433293042";
t= t.replace("TimeAcquired=",String.empty);
After just parse.
int mrt= int.parse(t);

Search for a sub-string within a string

I am really a beginner, I already know
string.indexOf("");
Can search for a whole word, but when I tried to search for e.g: ig out of pig, it doesn't work.
I have a similar string here(part of):
<Special!>The moon is crashing to the Earth!</Special!>
Because I have a lot of these in my file and I just cannot edited all of them and add a space like:
< Special! > The moon is crashing to the Earth! </ Special! >
I need to get the sub-string of Special! and The moon is crashing to the Earth!
What is the simple way to search for a part of a word without adding plugins like HTMLAgilityPack?
IndexOf will work, you are probably just using it improperly.
If your string is in a variable call mystring you would say mystring.IndexOf and then pass in the string you are looking for.
string mystring = "somestring";
int position = mystring.IndexOf("st");
How are you using it? You should use like this:
string test = "pig";
int result = test.IndexOf("ig");
// result = 1
If you want to make it case insensitive use
string test = "PIG";
int result = test.IndexOf("ig", StringComparison.InvariantCultureIgnoreCase);
// result = 1
String.IndexOf Method - MSDN
Please try this:
string s = "<Special!>The moon is crashing to the Earth!</Special!>";
int whereMyStringStarts = s.IndexOf("moon is crashing");
IndexOf should work with spaces too, but maybe you have new line or tab characters, not spaces?
Sometimes case-sensitivity is important. You may control it by additional parameter called comparisonType. Example:
int whereMyStringStarts = s.IndexOf("Special", StringComparison.OrdinalIgnoreCase);
More information about IndexOf: String.IndexOf Method at MSDN
Anyway, I think you may need regular expressions to create better parser. IndexOf is very primitive method and you may stuck in big mess of code.
string page = "<Special!>The moon is crashing to the Earth!</Special!>";
if (page.Contains("</Special!>"))
{
pos = page.IndexOf("<Special!>");
propertyAddress = page.Substring(10, page.IndexOf("</Special!>")-11);
//i used 10 because <special!> is 10 chars, i used 11 because </special!> is 11
}
This will give you "the moon is crashing to the earth!"

C# - Searching strings

I can't seem to find a good solution to this issue. I've got an array of strings that are fed in from a report that I recieve about lost or stolen equipment. I've been using the string.IndexOf function through the rest of the form and it works quite well. This issue is with the field that says if the device was lost or stolen.
Example:
"Lost or Stolen? Lost"
"Lost or Stolen? Stolen"
I need to be able to read this but when I do string.IndexOf(#"Lost") it will always return lost because it's in the question.
Unfortunately I'm not able to change the form itself in any way and due to the nature of how it's submited I can't just write code the knocks the first 15 or so characters off the string because that may be too few in some cases.
I would really like something in C# that would allow me to continue to search a string after the first result is found so that the logic would look like:
string my_string = "Lost or Stolen? Stolen";
searchFor(#"Stolen" in my_string)
{
Found Stolen;
Does it have "or " infront of it? yes;
ignore and keep searching;
Found Stolen again;
return "Equipment stolen";
}
Couple of options here. You could look for the last index of a space and take the rest of the string:
string input = "Lost or Stolen? Stolen";
int lastSpaceIndex = input.LastIndexOf(' ');
string result = input.Substring(lastSpaceIndex + 1);
Console.WriteLine(result);
Or you could split it and take the last word:
string input = "Lost or Stolen? Lost";
string result = input.Split(' ').Last();
Console.WriteLine(result);
Regex is also an option, but overkill given the simpler solutions above. A nice shortcut that fits this scenario is to use the RegexOptions.RightToLeft option to get the first match starting from the right:
string result = Regex.Match(input, #"\w+", RegexOptions.RightToLeft).Value;
If I understand your requirement, you're looking for an instance of Lost or Stolen after a ?:
var q = myString.IndexOf("?");
var lost = q >= 0 && myString.IndexOf("Lost", q) > 0;
var stolen = q >= 0 && myString.IndexOf("Stolen", q) > 0;
// or
var lost = myString.LastIndexOf("Lost") > myString.IndexOf("?");
var stolen = myString.LastIndexOf("Stolen") > myString.IndexOf("?");
// don't forget
var neither = !lost && !stolen;
You can look for the string 'Lost' and if it occurs twice, then you can confirm it is 'Lost'.
Its possible in this case that you could use index of on a substring knowing that it is always going to say lost or stolen first
so you parse out the lost or stolen, then like for you keyword to match the remaining string.
something like:
int questionIndex = inputValue.indexOf("?");
string toMatch = inputValue.Substring(questionIndex);
if(toMatch == "Lost")
If it works for your use case, it might be easier to use .EndsWith().
bool lost = my_string.EndsWith("Lost");

Using Regexp to get information in a KeyValuePair

Help me to parse this message:
text=&direction=re&orfo=rus&files_id=&message=48l16qL2&old_charset=utf-8&template_id=&HTMLMessage=1&draft_msg=&re_msg=&fwd_msg=&RealName=0&To=john+%3Cjohn11%40gmail.com%3E&CC=&BCC=&Subject=TestSubject&Body=%3Cp%3EHello+%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82+%D1%82%D0%B5%D0%BA%D1%81%D1%82%3Cbr%3E%3Cbr%3E%3C%2Fp%3E&secur
I would like to get information in an KeyValuePair:
Key - Value
text -
direction - re
and so on.
And how to convert this: Hello+%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82+%D1%82%D0%B5%D0%BA%D1%81%...
there are cyrillic character.
Thanks.
If you want to use a Regex, you can do it like this:
// I only added the first 3 keys, but the others are basically the same
Regex r = new Regex(#"text=(?<text>.*)&direction=(?<direction>.*)&orfo=(?<orfo>.*)");
Match m = r.Match(inputText);
if(m.Success)
{
var text = m.Groups["text"].Value; // result is ""
var direction = m.Groups["direction"].Value; // re
var orfo = m.Groups["orfo"].Value;
}
However, the method suggested by BoltClock is much better:
System.Collections.Specialized.NameValueCollection collection =
System.Web.HttpUtility.ParseQueryString(inputString);
It looks like you are dealing with a URI, better to use the proper class than try and figure out the detailed processing.
http://msdn.microsoft.com/en-us/library/system.uri.aspx

Categories

Resources