簡體   English   中英

我如何使用正則表達式Java提取值?

[英]how can i extract an value using regex java?

我需要單獨從此文本中提取數字,我使用子字符串提取一些細節,有時數字減少,所以我得到一個錯誤值...

 example(16656);

使用Pattern來編譯您的正則表達式,然后使用Matcher來獲取特定的捕獲組。 我正在使用的正則表達式是:

example\((\d+)\)

它捕獲括號內的數字( \\d+ )。 所以:

Pattern p = Pattern.compile("example\\((\\d+)\\)");
Matcher m = p.matcher(text);
if (m.find()) {
  int i = Integer.valueOf(m.group(1));
  ...
}

在這里查看Java正則表達式示例:

http://java.sun.com/developer/technicalArticles/releases/1.4regex/

特別着重於查找方法。

String yourString = "example(16656);";

Pattern pattern = Pattern.compile("\\w+\\((\\d+)\\);");
Matcher matcher = pattern.matcher(yourString);
if (matcher.matches())
{
    int value = Integer.parseInt(matcher.group(1));
    System.out.println("Your number: " + value);
}

我建議您編寫自己的邏輯來做到這一點。 使用Java的Pattern和Matcher東西是很好的做法,但是它們是標准解決方案,可能並不總是適合作為有效的解決方案。 像cletus提供了一個非常整潔的解決方案,但這種邏輯發生的是在后台執行子字符串匹配算法以跟蹤數字。 我想您不需要在這里找到模式。 您只需要從字符串中提取數字(例如從“ a1b2c3”中提取123)。請參見下面的代碼,該代碼在O(n)中以純凈的方式執行,並且不會像Pattern和Matcher類為您所做的那樣執行不必要的額外操作(只需復制並粘貼並運行:)):

公共類DigitExtractor {

/**
 * @param args
 */
public static void main(String[] args) {

    String sample = "sdhj12jhj345jhh6mk7mkl8mlkmlk9knkn0";

    String digits = getDigits(sample);

    System.out.println(digits);
}

private static String getDigits(String sample) {

    StringBuilder out = new StringBuilder(10);

    int stringLength = sample.length();

    for(int i = 0; i <stringLength ; i++)
    {
        char currentChar = sample.charAt(i);
        int charDiff = currentChar -'0';

        boolean isDigit = ((9-charDiff)>=0&& (9-charDiff <=9));

        if(isDigit)
            out.append(currentChar);

    }

    return out.toString();
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM