簡體   English   中英

Android,從長字符串中提取值

[英]android, extract value from long string

我有一個長字符串,我想解析和檢索一個值。 我當時在考慮使用模式,但對此我有些生疏。

這是我感興趣的字符串的一部分:

下沉成功率將達到44%

“下沉”是關鍵字。 我正在尋找百分比值(在這種情況下為44%)

什么是最好的方法? 謝謝。

**“將會是”一詞可能會更改。

如果始終是這種字符串,則為簡單的解決方案:

String splitMe = "...sinking will be 44% successful...";
String strPercents = splitMe.split(" ")[3];
System.out.println(strPercents);//test output

否則:好的正則表達式資源http://www.vogella.com/articles/JavaRegularExpressions/article.html#examples

這是一個正則表達式解決方案:

String str = "...sinking will be 44% successful...";
Pattern p = Pattern.compile( "sinking will be (\\S*) successful" );
Matcher m = p.matcher( str );
if ( m.find() ) {
    String percent = m.group( 1 );
}

如果只需要百分比的數字值,則將模式更改為此:

"sinking will be (\\d*)% successful"

如果上述任何文本均無關緊要,則只想獲取一行中的百分比,請使用以下模式:

"(\\d*%)"

編輯:如果您的關鍵字是“下沉”,並且您想要此單詞后的第一個百分比值,這將是您的模式:

"sinking(?:[\\w\\s]*) (\\d+%)"

只要您知道該文本始終以“下沉將”開頭,並且一個%始終存在,則不管周圍的文本如何

String s = "more text more text sinking will be 44% successful more text";
String find = "sinking will be ";
int findIndex = s.indexOf(find) + find.length();
int pctIndex = s.indexOf("%", findIndex);

String result = s.substring(findIndex , pctIndex);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM