2016-04-19 148 views
0

我想確定一個字符串是否包含特定的屬性。確定子字符串是否包含一個隨機數

我有一個很長的字符串,並要確定屬性,v_lstg_#,包含該字符串,但是,我有這個問題中是最後一個字符,在v_lstg_#,是任意整數,從0〜 9,(因此'#'),所以我的問題是什麼正則表達式(或任何其他方法)可以用來確定該屬性是否包含在字符串中?

所以類似於:

String randomString; 
randomString.contains("v_lstg_" + "some integer valued, ranged from 0 - 9, regex here") 
+0

沒有看到randomString'的'我們無法知道格式的例子。也就是說,我們可以把這個String看作一系列的字段嗎?領域如何呈現?這個字段後面的值的格式是什麼(即所有數字,字母數字,空格,空值,是否爲固定寬度......)一旦獲得了這些信息,您可能也會對潛在解決方案有所瞭解。也許正則表達式不是這樣做的正確方法? – jdv

+0

Obligatoratory:http://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/ – jdv

+0

@jdv嗯,字符串的格式確實是無關緊要的。假設我在一個句子中有兩個單詞,並且我想驗證該句子中包含「v_lstg_#」。唯一的問題是'#'是一個隨機整數。 – Robben

回答

0

你不想使用。這是一個正則表達式,在心臟,所以用matches()

boolean matches = randomString.matches(".*v_lstg_\\d.*"); 

ETA:已請求到v_lstg_部分從它的其餘部分分開:

String prefix = "v_lstg_"; 
boolean found = randomString.matches(".*"+prefix+"\\d.*"); 
+0

嗯有沒有辦法從你提供的正則表達式中分離單詞「v_lstg_」,所以像v_lstg_ +正則表達式?另外,爲了澄清,任意整數是從0到9. – Robben

+0

'\\ d'匹配任何單個數字,包括0。顯然,你可以拉出「v_lstg_」部分......參見編輯。我進一步注意到這將匹配多位數字。這似乎不是原始請求的一部分,但如果這是一個問題,則需要對正則表達式進行相應修改。 – dcsohl

0

這裏是另一個例子......使用正則表達式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 
相關問題