[英]How can I extract a dynamic length string from multiline string?
我正在使用“ nslookup”來從IP獲取計算機名稱。
nslookup 1.2.3.4
輸出是多行和機器名稱的長度動態字符。 如何從所有輸出中提取“ DynamicLengthString”。 所有建議IndexOf和Split ,但是當我嘗試那樣做時,對我來說不是一個好的解決方案。 有什么建議嗎?
Server: volvo.toyota.opel.tata
Address: 5.6.7.8
Name: DynamicLengthString.toyota.opel.tata
Address: 1.2.3.4
我在沒有正則表達式的情況下使用了Goold舊C#方式。
string input = @"Server: volvo.toyota.opel.tata
Address: 5.6.7.8
Name: DynamicLengtdfdfhString.toyota.opel.tata
Address: 1.2.3.4";
string targetLineStart = "Name:";
string[] allLines = input.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
string targetLine = String.Empty;
foreach (string line in allLines)
if (line.StartsWith(targetLineStart))
{
targetLine = line;
}
System.Console.WriteLine(targetLine);
string dynamicLengthString = targetLine.Remove(0, targetLineStart.Length).Split('.')[0].Trim();
System.Console.WriteLine("<<" + dynamicLengthString + ">>");
System.Console.ReadKey();
這將從給定輸入中提取“ DynamicLengtdfdfhString”,而不管名稱行在哪里,無論之后發生什么。 這是用於測試和驗證的控制台版本。
您可以使用正則表達式
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string Content = "Server: volvo.toyota.opel.tata \rAddress: 5.6.7.8 \rName: DynamicLengthString.toyota.opel.tata \rAddress: 1.2.3.4";
string Pattern = "(?<=DynamicLengthString)(?s)(.*$)";
//string Pattern = @"/^Dy*$/";
MatchCollection matchList = Regex.Matches(Content, Pattern);
Console.WriteLine("Running");
foreach(Match match in matchList)
{
Console.WriteLine(match.Value);
}
}
}
我將假設您的輸出與您所說的完全一樣。
string output = ExactlyAsInTheQuestion();
var fourthLine = output.Split(Environment.NewLine)[3];
var nameValue = fourthLine.Substring(9); //skips over "Name: "
var firstPartBeforePeriod = nameValue.Split('.')[0];
//firstPartBeforePeriod should equal "DynamicLengthString"
請注意,這是一個准系統示例:
IndexOutOfRangeException
。 Substring(9)
方法調整為Substring(6)
。 注意:我知道您解雇了Split
:
所有建議都是IndexOf和Split,但是當我嘗試那樣做時,對我來說不是一個好的解決方案。
但是僅根據此描述,就不可能知道問題是否在於讓Split
正常工作,或者實際上對您的情況不可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.