【问题标题】:How to pull phrase out of a string如何从字符串中提取短语
【发布时间】:2015-12-14 23:42:03
【问题描述】:

我如何将两个“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/ 测试了 regex("([0-9]+:[0-9]+)+") 并正确突出显示“8:16”

【问题讨论】:

标签: java regex


【解决方案1】:

您需要将捕获组放在第二个[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");

demo

【讨论】:

  • 好答案。这是最安全的方法。
  • matcher.find() 返回 false 会出现什么问题
  • 如果模式在输入字符串中的任何地方都不匹配,则返回结果为假。实际上,在大多数情况下,else 语句被省略了,我只是为了代码的完整性而添加了它。
【解决方案2】:

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); 

【讨论】:

  • 你在兜圈子。顺便说一句,我不知道“16”或“8”的值。只是它们中间有一个冒号,并且可能有更多的冒号
  • 如果值存储在变量中,你可以做同样的事情,除了你会这样做: Line.indexOf(String.valueOf(value));我到底是怎么绕圈子的?
  • 因为如果我们知道value 是什么,那么我们就可以做V = value
  • 很公平,所以你想在 :? 之后立即找到字符串?
  • 1,2,3 - 但它可能是 2 的第 2 个“:”或 8 的第 5 个,IDK,但它之前和之后会有 1-3 位数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
  • 2016-11-05
  • 2012-03-03
  • 1970-01-01
  • 2020-11-20
  • 2011-11-17
  • 1970-01-01
相关资源
最近更新 更多