簡體   English   中英

如何從一個字符串中拉出短語

[英]How to pull phrase out of a string

我如何為兩者拉出“16”

  • Bar Foo Bar:Foo8:16 Foo Bar Bar foo barz
  • 8:16 Foo Bar Bar foo barz

這是我嘗試過的

String V,Line ="Bar Foo Bar: Foo8:16 Foo Bar Bar foo barz";
V = Line.substring(Line.indexOf("([0-9]+:[0-9]+)+")+1);
V = V.substring(V.indexOf(":")+1, V.indexOf(" "));
System.out.println(V);

這是我得到的錯誤

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -9
    at java.lang.String.substring(String.java:1955)  
    at Indexing.Index(Indexing.java:94)  
    at Indexing.main(Indexing.java:24)

我在http://regexr.com/上測試了正則表達式(“([0-9] +:[0-9] +)+”),它正確地突出了“8:16”

您需要將捕獲組放在第二個[0-9]+ (或等效的\\d+ )上並使用Matcher#find()

String value1 = "Bar Foo Bar: Foo8:16 Foo Bar Bar foo barz";
String pattern1 = "\\d+:(\\d+)"; // <= The first group is the \d+ in round brackets
Pattern ptrn = Pattern.compile(pattern1);
Matcher matcher = ptrn.matcher(value1);
if (matcher.find())
    System.out.println(matcher.group(1)); // <= Print the value captured by the first group
else
    System.out.println("false");

演示

String.indexOf(String str)不接受正則表達式。 它需要一個字符串。

你可以這樣做:

String V, Line = "Bar Foo Bar: Foo8:16 Foo Bar Bar foo barz";
V = Line.substring(Line.indexOf("16"), Line.indexOf("16") + 2);
System.out.println(V);

或者為了使它看起來更整潔,你可以替換這一行:

V = Line.substring(Line.indexOf("16"), Line.indexOf("16") + 2);

有:

int index = Line.indexOf("16");
V = Line.substring(index, index + 2); 

暫無
暫無

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

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