![](/img/trans.png)
[英]How can I use indexof and substring to find words in a string?
[英]How can i use IndexOf to find an exact match?
我正在嘗試使用IndexOf查找字符串段的位置。 但是字符串可能看起來像這樣:
blahblahEAPPWForms
EAPPWTextblah blah
EAPPWblah
上面的示例可以按任何順序排列,但是有時我可能只是在尋找“ EAPPW”本身,而它可能根本不存在。 但是,如果首先出現“ EAPPWText”或“ EAPPWForms”,我得到它的索引。
您的問題有點令人困惑,因為它並不能真正解釋您是否僅想一直獲取"EAPPW"
字符串,還是要獲取它(如果存在)而沒有獲取,則不能以"EAPPW"
開頭
所以,這是如何同時獲得兩者的。 假設您要尋找"blah"
一詞,只有"blah"
一詞才可以使用正則表達式找到它。 此正則表達式在字符串的開頭,中間,結尾(如果是整個字符串)中搜索"blah"
。
搜索方法將返回第一次出現的索引。
x = "this is blah";
reg = /^blah$|^blah\s+|\s+blah\s+|\s+blah$/;
var location = x.search(reg);
如果要獲取“ blahaaa”(如果“ blah”不存在),則可以檢查結果是否為-1,然后執行indexOf。
if(location === -1)
{
location = x.indexOf("blah");
}
如果您只是在尋找沒有其他文字的實例,這非常簡單:
//Check if it's the whole string
if(str == "EAPPWText")
return 0;
//Check if it's in the start or end
int nIndex = str.IndexOf("EAPPWText" + " ");
if(nIndex >= 0)
return nIndex;
//Check if it's the LAST word
nIndex = str.IndexOf(" " + "EAPPWText" );
return nIndex;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.