在字符串中查找两个值之间的单词
我有一个txt文件作为字符串,我需要找到两个字符之间的单词和Ltrim
/ Rtrim
其他一切。 它可能必须是有条件的,因为两个字符可能会根据字符串而改变。
例:
car= (data between here I want) ; car = (data between here I want)
码:
int pos = st.LastIndexOf("car=", StringComparison.OrdinalIgnoreCase); if (pos >= 0) { server = st.Substring(0, pos);.............. }
这是我使用的一个简单的扩展方法:
public static string Between(this string src, string findfrom, string findto) { int start = src.IndexOf(findfrom); int to = src.IndexOf(findto, start + findfrom.Length); if (start < 0 || to < 0) return ""; string s = src.Substring( start + findfrom.Length, to - start - findfrom.Length); return s; }
有了它,你可以使用
string valueToFind = sourceString.Between("car=", "")
你也可以试试这个:
public static string Between(this string src, string findfrom, params string[] findto) { int start = src.IndexOf(findfrom); if (start < 0) return ""; foreach (string sto in findto) { int to = src.IndexOf(sto, start + findfrom.Length); if (to >= 0) return src.Substring( start + findfrom.Length, to - start - findfrom.Length); } return ""; }
有了它,你可以给出多个结束标记(它们的顺序很重要)
string valueToFind = sourceString.Between("car=", ";", "")
你可以使用正则表达式
上述就是C#学习教程:在字符串中查找两个值之间的单词分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
var input = "car= (data between here I want) ;"; var pattern = @"car=s*(.*?)s*;"; // where car= is the first delimiter and ; is the second one var result = Regex.Match(input, pattern).Groups[1].Value;
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1029024.html