문자열에서 좌표를 추출하고 싶습니다.정규 표현식을 사용하여 문자열에서 좌표를 추출하는 더 나은 방법
string Coord = @"
at point X=-277923.7300 Y=16462.7700 Z= 0.0000
at point X=-277816.6200 Y=16311.1500 Z= 0.0000
at point X=-277629.1900 Y=16109.7100 Z= 0.0000
at point X=-277573.4000 Y=16055.5600 Z= 0.0000
at point X=-277524.3100 Y=16023.0700 Z= 0.0000
at point X=-277508.6900 Y=15986.2400 Z= 0.0000
at point X=-277488.6100 Y=15866.0200 Z= 0.0000
at point X=-277466.3000 Y=15766.3800 Z= 0.0000
at point X=-277421.6700 Y=15710.0700 Z= 0.0000
at point X=-277281.0900 Y=15595.2700 Z= 0.0000
at point X=-277234.2300 Y=15547.6100 Z= 0.0000
at point X=-277185.1400 Y=15469.6400 Z= 0.0000
at point X=-277091.4900 Y=15354.1300 Z= 0.0000:;
내가 좌표 목록에 모든 X와 Y를합니다 (Z에 대한주의를 해달라고) 추출 할 :
내가 가진 문자열이 양식을 가지고있다.
이는 좌표 클래스입니다 : 내가 Regex
를 사용하는 것이 좋습니다했다
public class Coordinates
{
public double Longitude { get; set; }
public double Latitude { get; set; }
public Coordinates(double Long, double Lat)
{
this.Longitude = Long;
this.Latitude = Lat;
}
}
내가 그것을 completly 새로운 이후, 좀 고생하지만 준비가 뭔가를 할 수 있었다.
이것은 내가 지금까지 무엇을했는지 있습니다 :
private List<Coordinates> ExtractCoordinates(string Coordinates)
{
List<Coordinates> lstOfCoordinates = new List<Coordinates>();
//I managed to put this regex together after some trial and error
//This regex will extract this pattern : " X=(any decimal) Y=(any decimal)"
Regex reg = new Regex("(X=)-?\\d+\\.?\\d+\\s+(Y=)-?\\d+\\.?\\d+");
//I get the matches and save them in a list
MatchCollection collection = reg.Matches(Coord);
List<string> lstOfMatches = (from Match match in collection
select match.Value).ToList();
//At this point I have alist of string having this form: "X=-277923.7300 Y=16462.7700"
//I had no idea how to proceed from here so I did it in a bad way
//Basically I just Cut the string when I detect the first '='
//and then take the rest until the Y. I remove the = and trim it
//and then parse it to double this is the X
//Same logic for the Y coordinates
foreach (string match in lstOfMatches)
{
double X = double.Parse(match.Substring(match.IndexOf('='), match.IndexOf('Y') - match.IndexOf('=')).Replace("=","").Trim());
double Y = double.Parse(match.Substring(match.IndexOf("Y=")).Replace("Y=", "").Trim());
lstOfCoordinates.Add(new Coordinates(X, Y));
}
return lstOfCoordinates;
}
음은 기본적으로 작동하지만 난 그것을 할 수있는 좋은 방법이 아니다 생각합니다.
그래서 더 나은 방법을 찾고 있습니다. 어쩌면 Regex 만 사용하거나 더 깨끗한 방법으로 제안을 사용하여 전체 논리를 수행하십시오.
감사합니다.