【发布时间】:2012-12-24 07:12:40
【问题描述】:
我正在尝试编写一个 Java 方法,它将一个字符串作为参数,如果它匹配一个模式,则返回另一个字符串,否则返回 null。模式:
- 以数字开头(1 位以上);然后是
- 冒号(“
:”);然后是 - 单个空格(“”);然后是
- 任何 1+ 个字符的 Java 字符串
因此,一些与此模式匹配的有效字符串:
50: hello
1: d
10938484: 394958558
还有一些不与此模式匹配的字符串:
korfed49
: e4949
6
6:
6:sdjjd4
该方法的大致框架是这样的:
public String extractNumber(String toMatch) {
// If toMatch matches the pattern, extract the first number
// (everything prior to the colon).
// Else, return null.
}
这是我迄今为止最好的尝试,但我知道我错了:
public String extractNumber(String toMatch) {
// If toMatch matches the pattern, extract the first number
// (everything prior to the colon).
String regex = "???";
if(toMatch.matches(regex))
return toMatch.substring(0, toMatch.indexOf(":"));
// Else, return null.
return null;
}
提前致谢。
【问题讨论】: