我想从一个用空格(“”)和逗号分隔的String中获取一个String数组。有一个聪明的方法吗?
例如,如果字符串是:
猫狗长颈鹿“大象”蛇
我希望结果数组包含字符串
猫
狗
长颈鹿
大象
蛇
我知道我可以做一个Split(str,“”),但结果会与我想要的不同。我从来没有使用过RegEx,但我有一种预感,解决方案可能与它有关。
答案 0 :(得分:3)
将输入视为以空格分隔的CSV可以极大地简化任务:
Imports Microsoft.VisualBasic.FileIO.TextFieldParser
...
Dim s As String = "cat dog giraffe ""big elephant"" snake"
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(New System.IO.StringReader(s))
Dim CurrentRecord As String()
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {" "}
afile.HasFieldsEnclosedInQuotes = True
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
Console.WriteLine(String.Join("; ", CurrentRecord))
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
打印cat; dog; giraffe; big elephant; snake
。
答案 1 :(得分:0)
您可以使用正则表达式:
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
//get the values from the dropdownlists
decimal selectedValue1 = Convert.ToDecimal(DropDownList1.SelectedValue);
decimal selectedValue2 = Convert.ToDecimal(DropDownList2.SelectedValue);
//clear all listitems from dropdownlist3
DropDownList3.Items.Clear();
//add the listitems based on the selected values
if (selectedValue1 > selectedValue2)
{
DropDownList3.Items.Insert(0, new ListItem("MET", "MET", true));
}
else if (selectedValue1 < selectedValue2)
{
DropDownList3.Items.Insert(0, new ListItem("Breached", "Breached", true));
}
else
{
DropDownList3.Items.Insert(0, new ListItem("Threatened", "Threatened", true));
}
}
正则表达式的工作原理如下:
然后我们只需要Const data = "åäöÄ åäöÄ ""åäöÄ åäöÄ"" åäöÄ"
Dim matches = Regex.Matches (data, "\p{L}+|""\p{L}+(?: \p{L}+)*""")
For Each m As Match in matches
Console.WriteLine (m.Value.Trim(""""))
Next
得到的匹配就可以消除潜在的startind / end quote
注意:有关Trim