我如何在正则表达式中捕获这个纬度值

本文关键字:纬度 正则表达式 | 更新日期: 2023-09-27 18:13:28

我正在调用一个服务,它会像这样返回我的经纬度:"Lat:42.747058 Long:-84.551892" .

如何使用正则表达式捕获纬度值?这段代码不能运行。

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;

我如何在正则表达式中捕获这个纬度值

试试这个regex:

(?<=Lat:)(-?'d+'.'d+)
在c#:

Regex.Matches(GPSLocation, "(?<=Lat:)(-?''d+''.''d+)")[0].Value;

它只是匹配一个带有可选- -符号的十进制数。

我不会在这样简单的事情上使用正则表达式

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;

希望你不介意我放一个非正则表达式的解决方案

    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:()"将匹配" late:",然后捕获一个空字符串。在括号内,您需要添加想要捕获的字符,如:"Lat:([-.0-9]*)"

应该可以:

Lat:(['d.-]+) Long:(['d.-]+)

with this String: string GPSLocation = "Lat:42.747058 Long:-84.551892";您可以先使用Split(':')然后使用Split(' '): string s=GPSLocation.Split(':')[1].Split(' ')[0]然后s Lat。

尝试:

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无耻地从RegexLib.com窃取

确保你的反斜杠是双倍的

使用一个可以反复编译和使用的regex对象

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;