简体   繁体   English

我如何使用正则表达式Java提取值?

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

我需要单独从此文本中提取数字,我使用子字符串提取一些细节,有时数字减少,所以我得到一个错误值...

 example(16656);

Use Pattern to compile your regular expression and Matcher to get a particular captured group. 使用Pattern来编译您的正则表达式,然后使用Matcher来获取特定的捕获组。 The regex I'm using is: 我正在使用的正则表达式是:

example\((\d+)\)

which captures the digits ( \\d+ ) within the parentheses. 它捕获括号内的数字( \\d+ )。 So: 所以:

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

look at Java Regular Expression sample here: 在这里查看Java正则表达式示例:

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

specially focus on find method. 特别着重于查找方法。

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);
}

I will suggest you to write your own logic to do this. 我建议您编写自己的逻辑来做到这一点。 Using Pattern and Matcher things from java are good practice but these are standard solutions and may not suit as a solution in effective manner always. 使用Java的Pattern和Matcher东西是很好的做法,但是它们是标准解决方案,可能并不总是适合作为有效的解决方案。 Like cletus provided a very neat solution but what happens in this logic is that a substring matching algorithm is performed in the background to trace digits. 像cletus提供了一个非常整洁的解决方案,但这种逻辑发生的是在后台执行子字符串匹配算法以跟踪数字。 You do not need the pattern finding here I suppose. 我想您不需要在这里找到模式。 You just need to extract the digits from a string (like 123 from "a1b2c3") .See the following code which does it in clean manner in O(n) and does not perform unnecessary extra operation as Pattern and Matcher classes do for you (just do copy and paste and run :) ): 您只需要从字符串中提取数字(例如从“ a1b2c3”中提取123)。请参见下面的代码,该代码在O(n)中以纯净的方式执行,并且不会像Pattern和Matcher类为您所做的那样执行不必要的额外操作(只需复制并粘贴并运行:)):

public class DigitExtractor { 公共类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