I'm calling a service that gives me back a latitude and longitude like this: "Lat:42.747058 Long:-84.551892".
How do I capture the latitude value using regular expressions?
This code does not work.
string GPSLocation = "Lat:42.747058 Long:-84.551892";
MatchCollection matches = Regex.Matches(GPSLocation, "Lat:() ");
if (matches.Count > 0)
{
string latValue = matches[0].Value;
return Decimal.Parse(latValue);
}
return 0M;
Try this regex:
(?<=Lat:)(-?\d+\.\d+)
In C#:
Regex.Matches(GPSLocation, "(?<=Lat:)(-?\\d+\\.\\d+)")[0].Value;
It simply matches a decimal number with an optional --sign.
I wouldn't use regex for something simple like this
How about
string GPSLocation = "Lat:42.747058 Long:-84.551892";
var values = GPSLocation.split(" ");
if (values.Count > 0)
{
string lat = values[0].split(":")[1];
return Decimal.Parse(lat);
}
return 0M;
Hope you don't mind me putting a non-regex solution
string GPSLocation = "Lat:42.747058 Long:-84.551892";
string lat = GPSLocation.Substring(4, GPSLocation.IndexOf("Long") - 5);
string lon = GPSLocation.Substring(GPSLocation.IndexOf("Long") + 5);
"Lat:()" will match "Lat:", then capture an empty string. Inside the parentheses you need to add the characters you want to capture, like this: "Lat:([-.0-9]*)".
This should work:
Lat:([\d.-]+) Long:([\d.-]+)
with this String:string GPSLocation = "Lat:42.747058 Long:-84.551892";You can first use Split(':') then Use Split(' '): string s=GPSLocation.Split(':')[1].Split(' ')[0] then s Lat.
Try:
string GPSLocation = "Lat:42.747058 Long:-84.551892";
string latRegex = "Lat:-?([1-8]?[1-9]|[1-9]?0)\\.{1}\\d{1,6}"
MatchCollection matches = Regex.Matches(GPSLocation, latRegex);
if (matches.Count > 0)
{
...
Regex shamelessly stolen from RegexLib.com
Make sure to double up on your backslashes
With use of a regex object which you could compile and use again and again.
Decimal res;
string GPSLocation = "Lat:42.747058 Long:-84.551892";
Regex regexObj = new Regex(#"(?<=Lat:)-?(\b[0-9]+(?:\.[0-9]+)?\b)");
if (Decimal.TryParse(regexObj.Match(GPSLocation).Groups[1].Value, out res)){
return res;
}
return 0M;
Related
I want to remove word Test and Leaf from the specified string beginning only,not from the other side,so string Test_AA_234_6874_Test should be AA_234_6874_Test,But when i use .Replace it will replace word Test from everywhere which i don't want.How to do it
This is the code what i have done it
string st = "Test_AA_234_6874_Test";
st = st.Replace("Test_","");
You could use a regex to do this. The third argument of the regex replace method specifics how many times you want to replace.
string st = "Test_AA_234_6874_Test";
var regex = new Regex("(Test|Leaf)_");
var value = regex.Replace(st, "", 1);
Or if the string to replace only occurs on the start just use ^ which asserts the position at start of the string.
string st = "Test_AA_234_6874_Test";
var regex = new Regex("^(Test|Leaf)_");
var value = regex.Replace(st, "");
If you know that you allways have to remove the first 5 letters you can also use Substring which is more performant.
string st = "Test_AA_234_6874_Test";
var value = st.Substring(5, st.Length - 5);
The simplest way to do this is by using a Regular Expression like so.
using System;
using System.Text.RegularExpressions;
using System.Text;
namespace RegExTest
{
class Program
{
static void Main(string[] args)
{
var input = "Test_AA_234_6874_Test";
var matchText = "Test";
var replacement = String.Empty;
var regex = new Regex("^" + matchText);
var output = regex.Replace(input, replacement);
Console.WriteLine("Converted String: {0}", output);
Console.ReadKey();
}
}
}
The ^ will match text at the beginning of the string.
Consider checking whether the string starts with "Start" and/or ends with "Trim" and decide the end and start positions you'd like to maintain. Then use Substring method to get only the portion you need.
public string Normalize(string input, string prefix, string suffix)
{
// Validation
int length = input.Length;
int startIndex = 0;
if(input.StartsWith(prefix))
{
startIndex = prefix.Length;
length -= prefix.Length;
}
if (input.EndsWith (suffix))
{
length -= suffix.Length;
}
return input.Substring(startIndex, length);
}
Hope this helps.
string wordToRemoveFromBeginning = "Test_";
int index = st.IndexOf(wordToRemoveFromBeginning);
string cleanPath = (index < 0) ? st : st.Remove(index,
wordToRemoveFromBeginning.Length);
Use a regular expression.
var str1 = "Test_AA_234_6874_Test";
var str2 = "Leaf_AA_234_6874_Test";
str1 = Regex.Replace(str1, "^Test", "");
str2 = Regex.Replace(str2, "^Leaf", "");
Regex.Replace parameters are your input string (str1), the pattern you want to match, and what to replace it with, in this case a blank space. The ^ character means look at the start of the string, so something like "MyTest_AAAA_234_6874_Test" would stil return "MyTest_AA_234_6874_Test".
I am gonna use some very simple code here
string str = "Test_AA_234_6874_Test";
string substring = str.Substring(0, 4);
if (substring == "Test" || substring == "Leaf")
{
str= str.Remove(0, 5);
}
Usually, we can easily get a String value between two characters. My question is, how do I get the value between two same characters.
For example:
String full_value = "http://stackoverflow.com/questions/9367119/title-goes-here";
In this example, how can I extract the value 9367119 from the entire string?
The solution that I use doesn't work since 9367119 has the same / characters to the right and left of it.
Here's what I have so far:
This works for values that doesn't have two same characters to the left and right. Such as: /dog\ I can easily replace / and \ with my solution
public static string Between(string full_value, string a, string b)
{
int posA = full_value.IndexOf(a);
int posB = full_value.LastIndexOf(b);
if (posA == -1)
{
return "";
}
if (posB == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
if (adjustedPosA >= posB)
{
return "";
}
return full_value.Substring(adjustedPosA, posB - adjustedPosA);
}
You could just Split and get the relevant part:
string s = "http://stackoverflow.com/questions/9367119/title-goes-here";
string[] sp = s.Split('/');
Console.WriteLine(sp[4]);
IdeOne demo.
Use following regex:
(?<=/)\d+(?=/)
String full_value = "http://stackoverflow.com/questions/9367119/title-goes-here";
var matches = Regex.Matches(full_value, #"(?<=/)\d+(?=/)");
try this way use Split
string s = "http://stackoverflow.com/questions/9367119/title-goes-here";
string[] sps = s.Split('/');
foreach(string sp in sps ){
if(sp =="9367119"){
Console.WriteLine(sp);
}
}
I want to trim a string after a special character..
Lets say the string is str="arjunmenon.uking". I want to get the characters after the . and ignore the rest. I.e the resultant string must be restr="uking".
How about:
string foo = str.EverythingAfter('.');
using:
public static string EverythingAfter(this string value, char c)
{
if(string.IsNullOrEmpty(value)) return value;
int idx = value.IndexOf(c);
return idx < 0 ? "" : value.Substring(idx + 1);
}
you can use like
string input = "arjunmenon.uking";
int index = input.LastIndexOf(".");
input = input.Substring(index+1, input.Split('.')[1].ToString().Length );
Use Split function
Try this
string[] restr = str.Split('.');
//restr[0] contains arjunmenon
//restr[1] contains uking
char special = '.';
var restr = str.Substring(str.IndexOf(special) + 1).Trim();
Try Regular Expression Language
using System.IO;
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "arjunmenon.uking";
string pattern = #"[a-zA-Z0-9].*\.([a-zA-Z0-9].*)";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
}
}
}
Result:
arjunmenon.uking
Group 1: uking
Personally, I won't do the split and go for the index[1] in the resulting array, if you already know that your correct stuff is in index[1] in the splitted string, then why don't you just declare a constant with the value you wanted to "extract"?
After you make a Split, just get the last item in the array.
string separator = ".";
string text = "my.string.is.evil";
string[] parts = text.Split(separator);
string restr = parts[parts.length - 1];
The variable restr will be = "evil"
string str = "arjunmenon.uking";
string[] splitStr = str.Split('.');
string restr = splitStr[1];
Not like the methods that uses indexes, this one will allow you not to use the empty string verifications, and the presence of your special caracter, and will not raise exceptions when having empty strings or string that doesn't contain the special caracter:
string str = "arjunmenon.uking";
string restr = str.Split('.').Last();
You may find all the info you need here : http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx
cheers
I think the simplest way will be this:
string restr, str = "arjunmenon.uking";
restr = str.Substring(str.LastIndexOf('.') + 1);
Is there any way to take a part out of a regex? Let's say I have a match for this
\s*(string)\s*(.*\()\s*(\d*)\)\s*;?(.*)
and I want to change it like this
Regex.Replace(line, #"\s*(string)\s*(.*\()\s*(\d*)\)\s*;?(.*)", "$1 $2($3) // $4", RegexOptions.IgnoreCase);
Is there any way I can grab the $4 by itself and set it equal to some string variable?
Let's say the regex match is: string (55) ;comment
In this case I'd like to get the word comment only and set it to a string without going through the String.Split function. Ultimately, though, I'd just like to get the digits between the parentheses.
There's an overload for the Replace method which takes a MatchEvaluator delegate:
string pattern = "...";
string result = Regex.Replace(line, pattern, m =>
{
int digits = 0;
string comment = m.Groups[4].Value; // $4
int.TryParse(m.Groups[3].Value, out digits); // $3
return string.Format("{0} {1}({2}) // {3}",
m.Groups[1].Value, m.Groups[2].Value, digits, comment);
}, RegexOptions.IgnoreCase);
Hope this helps.
Yes, if I understand the question correctly:
var re = new Regex(#"\s*(string)\s*(.*\()\s*(\d*)\)\s*;?(.*)");
var match = re.Match(input);
if (match.Success)
{
int i = match.Groups[4].Index;
int n = match.Groups[4].Length;
input = input.Substring(0, i) + replacementString + input.Substring(i + n);
}
I have a file name: kjrjh20111103-BATCH2242_20111113-091337.txt
I only need 091337, not the txt or the - how can I achieve that. It does not have to be 6 numbers it could be more or less but will always be after "-" and the last ones before ."doc" or ."txt"
You can either do this with a regex, or with simple string operations. For the latter:
int lastDash = text.LastIndexOf('-');
string afterDash = text.Substring(lastDash + 1);
int dot = afterDash.IndexOf('.');
string data = dot == -1 ? afterDash : afterDash.Substring(0, dot);
Personally I find this easier to understand and verify than a regular expression, but your mileage may vary.
String fileName = kjrjh20111103-BATCH2242_20111113-091337.txt;
String[] splitString = fileName.Split ( new char[] { '-', '.' } );
String Number = splitString[2];
Regex: .*-(?<num>[0-9]*). should do the job. num capture group contains your string.
The Regex would be:
string fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
string fileMatch = Regex.Match(fileName, "(?<=-)\d+", RegexOptions.IgnoreCase).Value;
String fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
var startIndex = fileName.LastIndexOf('-') + 1;
var length = fileName.LastIndexOf('.') - startIndex;
var output = fileName.Substring(startIndex, length);