[英]how do i get the position in the original string where the last character of the captured substring found
大家好,這是我的原始字符串'010000111'
我需要找到這種模式'10000111'。所以我在正則表達式下面使用了這一點。
匹配m = Regex.Match(“ 010000111”,@“ [1] [0] [0] [0] [0] [1] +”);
我從正則表達式中得到了正確的答案。但是問題是我需要在原始字符串中獲取捕獲的字符串的最后一個字符的位置,根據我的示例,這意味着我捕獲的模式為``10000111''我的最后一個索引是7,但是當與原始字符串進行比較時,它是8。
我使用了lastIndexOf('1')函數。但是它給出了捕獲的字符串的索引。
你能幫我解決這個問題嗎?
您不需要正則表達式即可執行此操作。
要檢查字符串是否包含另一個字符串,請使用someString.IndexOf("someOtherString")
方法。 這將為您提供序列中第一個字符的索引。
要獲取最后一個字符的位置,您要做的就是將測試字符串的長度相加並減去1:
var firstString = "010000111";
var secondString = "10000111";
var positionOfSecondOverFirst = firstString.IndexOf(secondString); // 1
var firstContainsSecond = (positionOfSecondOverFirst >= 0); // true
var positionOfLastChar = positionOfSecondOverFirst + secondString.Length - 1; // 8
參考: https : //msdn.microsoft.com/library/k8b1470s(v=vs.110).aspx
您為什么要使用正則表達式的任何特殊原因? 我認為您要完成的任務只需使用IndexOf
即可完成
public static int GetIndex()
{
const string input = "010000111";
const string substring = "10000111";
var startIndex = input.IndexOf(substring);
if (startIndex != -1)
{
return startIndex + substring.Length;
}
return -1;
}
您可以使用以下方法:
private int findLastIndex(string s1, string s2)
{
if (s1.indexOf(s2)>-1)
{
return s1.indexOf(s2) + s2.Length - 1;
}
else
return -1; //not found
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.