2

我正在使用此代码获取有关我的 IP 地址的信息

protected void Page_Load(object sender, EventArgs e)
{

    WebRequest request = WebRequest.Create("http://gd.geobytes.com/gd?after=-1&variables=GeobytesCountry,GeobytesCity,GeobytesRegion,GeobytesLatitude,GeobytesLongitude");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream dataStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(dataStream);
    var responseFromServer = reader.ReadToEnd();
    Label1.Text = responseFromServer.ToString();
    reader.Close();
    dataStream.Close();
    response.Close();
}

它返回到label1

var sGeobytesLocationCode="PKPBRAWA";
var sGeobytesIsLocationMatch=false;
var sGeobytesCountry="Pakistan";
var sGeobytesRegion="Punjab";
var sGeobytesCity="Rawalpindi";
var sGeobytesLatitude="33.6000";
var sGeobytesLongitude="73.0670";

我如何从中仅获取城市名称。就我而言,拉瓦尔品第

4

1 回答 1

1

试试这个

string temp = responseFromServer.ToString();

Match _matchdec = Regex.Match(temp, @"\ssGeobytesCity=""\b(\S*)\b""", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
if (_matchdec.Success)
{
   string retval = _matchdec.Groups[1].Value;   
   Label1.Text = retval ;  
}

添加命名空间using System.Text.RegularExpressions

希望这有帮助。

于 2013-03-20T08:05:08.027 回答