這裏是另一個例子......使用正則表達式Pattern和Matcher類。如果你只想要數字,那麼你可以研究正則表達式分組來解決這個問題。正則表達式可能會發瘋,所以要小心。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Debug {
public static void main(String[] args) {
String s = "v_lstg_124536someotherstuff";
String regex = "(v_lstg_\\d+)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
System.out.println(m.find());
System.out.println(s.subSequence(m.start(), m.end()));
}
}
這裏是與德分組
public static void main(String[] args) {
String s = "v_lstg_124536someotherstuff";
String regex = "(v_lstg_)(\\d+)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
System.out.println(m.find());
System.out.println(s.subSequence(m.start(), m.end()));
System.out.println(m.group(1));
System.out.println(m.group(2));
}
它打印
true
v_lstg_124536
v_lstg_
124536
沒有看到randomString'的'我們無法知道格式的例子。也就是說,我們可以把這個String看作一系列的字段嗎?領域如何呈現?這個字段後面的值的格式是什麼(即所有數字,字母數字,空格,空值,是否爲固定寬度......)一旦獲得了這些信息,您可能也會對潛在解決方案有所瞭解。也許正則表達式不是這樣做的正確方法? – jdv
Obligatoratory:http://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/ – jdv
@jdv嗯,字符串的格式確實是無關緊要的。假設我在一個句子中有兩個單詞,並且我想驗證該句子中包含「v_lstg_#」。唯一的問題是'#'是一個隨機整數。 – Robben