我正在尝试以C#格式从html对象导入一些文本。
var a = document.getElementById('js_CityPosition0Link').title;
console.log(a);
var b = a.split(" (");
console.log(b);
var c = b[0];
console.log(c);
我可以获取“ a”字符串,但不能像javascript那样以C#语言转换为“ c”。
您必须将其转换为数组,然后才能分割字符串
string str = "Belediye Binasi (10)";
string[] str_toArray = str.Split('(');
foreach(string val in str_toArray)
{
Console.WriteLine(val);
}
Console.WriteLine("The result you need : {0}", str_toArray[0]);
Console.ReadKey();
结果:
Belediye Binasi
10)
The result you need : Belediye Binasi
代替使用Split或Substring或IndexOf和其他字符串操作函数,您可以在一行Regex中完成它:
string a = "Belediye Binasi (10)";
string c = Regex.Match(a, @"^(.+) \(\d+\)$").Groups[1].Value;
[在其他情况下,例如a
为Belediye (Ye Boi) Binasi (10)
时,也不太容易出错。
拆分非常适合当您实际想要将某些部分拆分(例如属性列表),但是从常规文本中提取数据(表示格式不变)时,使用正则表达式是最好的方法。