简体   繁体   English

使用Google Guava获取字符串的前导数字

[英]Getting leading digits of a string using Google Guava

Basically, I have some strings like 基本上,我有一些像

5 - Avenue Rd
9 - Bellamy
21 - Brimley
191 - Highway 27 Rocket

And so on. 等等。 I'm looking for a way using Google Guava to return the beginning digits. 我正在寻找一种使用Google Guava返回起始数字的方法。 From what I've researched: 根据我的研究:

  • CharMatcher.DIGIT.retainFrom is nice but I want it to stop at the first non-digit character. CharMatcher.DIGIT.retainFrom很不错,但我希望它在第一个非数字字符处停止。
  • CharMatcher.DIGIT.trimLeadingFrom is pretty much what I want, except that it returns the other part of the string where I want a string of digits instead. CharMatcher.DIGIT.trimLeadingFrom几乎是我想要的,除了它返回字符串的另一部分(我想要的是一串数字)。

Any ideas? 有任何想法吗?

EDIT: added another example. 编辑:添加了另一个示例。

Expected output for the four examples above: 上面四个示例的预期输出:

5
9
21
191

Not quite equivalent, but 不太相等,但是

CharMatcher.DIGIT.negate().trimTrailingFrom(string);

Or -- a bit more involved, but this will work with intermediate digits -- 或者-涉及更多一点,但这将适用于中间数字-

string.substring(0, CharMatcher.DIGIT.negate().indexIn(string));

Or, with regexes, albeit with all the overhead that implies -- 或者,使用正则表达式,尽管意味着所有开销-

string.replaceAll("^(\\d+).*$", "$1")

Why don't you just split() the string on the "-" sign and then trim() and parse... 您为什么不只将“-”号上的字符串split() ,然后trim()并解析...

String test ="5 - Avenue Rd";
String[] out = test.split("-");
System.out.println(out[0].trim());

We don't need a framework to do that. 我们不需要框架来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM