請教大家
要如何抓出一段文字中指定的參數spaceKey後的參數呢?spaceKey後的參數會有2-6碼的文字,接著使用&符號來串接其他參數,資料儲存的內容如下
/plugins/editor-loader/editor.action?parentPageId=&pageId=47120991&spaceKey=NN&atl_after_login_redirect=%2Fpages%2Fviewpage.action&timeout=12000&_=1498533190644 HTTP/1.1 43742 200 http-nio-8090-exec-9
謝謝
給你一個範例
using System.Text.RegularExpressions;
... ...
string input = "/plugins/editor-loader/editor.action?parentPageId=&pageId=47120991&spaceKey=NN&atl_after_login_redirect=%2Fpages%2Fviewpage.action&timeout=12000&_=1498533190644 HTTP/1.1 43742 200 http-nio-8090-exec-9";
string pattern = @"spaceKey=(?<word>[\s\S]+?)&";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(input); // 將比對後集合傳給 MatchCollection
int index = 0;
foreach (Match match in matches) // 一一取出 MatchCollection 內容
{
// 將 Match 內所有值的集合傳給 GroupCollection groups
GroupCollection groups = match.Groups;
// 印出 Group 內 word 值
Console.WriteLine(++index + ": " + groups["word"].Value.Trim());
}
執行出來的結果就是 1 NN
其中groups["word"].Value.Trim()取出來的就會是你要的值,
雖然我用了foreach,不過你這個例子應該只會抓到一個值而已,
如果要了解深一點
請搜尋 Regex 和 正規表示式
請教前輩
我參考MSDN VB的範例,修改如下結果
If Not IsPostBack Then
Dim strDbCon As String = "Data Source=(local);Initial Catalog=DB14017;Persist Security Info=True;User ID=sa;Password=5342601water"
Dim con As New SqlConnection(strDbCon)
Dim ad As New SqlDataAdapter("SELECT [f1],[f2] FROM [DB].[dbo].[5] where f2 like '%viewpage%'", con)
Dim dt As New DataTable
ad.Fill(dt)
If dt.Rows.Count > 0 Then
Label1.Text = IIf(dt.Rows(0).IsNull("f2"), "", dt.Rows(0)("f2"))
Dim pattern As String = "spaceKey=(?<word>[\s\S]+?)&"
Dim regex As Regex = New Regex(pattern, RegexOptions.IgnoreCase)
Dim matches As MatchCollection = regex.Matches(dt.Rows(0).IsNull("f2"))
Dim index As Integer = 0
For Each m As Match In regex.Matches(Match, pattern)
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index)
Next
End If
但會出現下列的訊息,是否有建議的方向呢?謝謝
先用String.IndexOf找出空白所在的字串的位置
https://msdn.microsoft.com/zh-tw/library/k8b1470s(v=vs.110).aspx
再用String.Substring取出您所要2~6碼長度的字串
https://msdn.microsoft.com/zh-tw/library/aka44szs(v=vs.110).aspx