Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中使用正则表达式提取值_Java_Regex - Fatal编程技术网

在Java中使用正则表达式提取值

在Java中使用正则表达式提取值,java,regex,Java,Regex,我有几个粗略的字符串: [some text] [some number] [some more text] 我想使用Java正则表达式类提取[some number]中的文本 我大致知道我想要使用什么正则表达式(尽管欢迎所有建议)。我真正感兴趣的是获取regex字符串并在源数据上使用它来生成[some number]值的Java调用 编辑:我应该补充一点,我只对一个[某个数字]感兴趣(基本上是第一个例子)。源字符串很短,我不会寻找[某个数字]的多次出现。完整示例: private stati

我有几个粗略的字符串:

[some text] [some number] [some more text]
我想使用Java正则表达式类提取[some number]中的文本

我大致知道我想要使用什么正则表达式(尽管欢迎所有建议)。我真正感兴趣的是获取regex字符串并在源数据上使用它来生成[some number]值的Java调用

编辑:我应该补充一点,我只对一个[某个数字]感兴趣(基本上是第一个例子)。源字符串很短,我不会寻找[某个数字]的多次出现。

完整示例:

private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
    // create matcher for pattern p and given string
    Matcher m = p.matcher("Testing123Testing");

    // if an occurrence if a pattern was found in a given string...
    if (m.find()) {
        // ...then you can use group() methods.
        System.out.println(m.group(0)); // whole matched expression
        System.out.println(m.group(1)); // first expression from round brackets (Testing)
        System.out.println(m.group(2)); // second one (123)
        System.out.println(m.group(3)); // third one (Testing)
    }
}
由于您正在查找第一个数字,因此可以使用以下regexp:

^\D+(\d+).*
m.group(1)
将返回第一个号码。请注意,有符号的数字可以包含减号:

^\D+(-?\d+).*
在Java 1.4及更高版本中:

String input = "...";
Matcher matcher = Pattern.compile("[^0-9]+([0-9]+)[^0-9]+").matcher(input);
if (matcher.find()) {
    String someNumberStr = matcher.group(1);
    // if you need this to be an int:
    int someNumberInt = Integer.parseInt(someNumberStr);
}

Allain基本上有java代码,所以您可以使用它。但是,他的表达式仅在数字前面有一系列单词字符时匹配

"(\\d+)"
应该能够找到第一个数字串。如果确定它将是第一个数字字符串,则不需要指定它前面的内容。同样,除非您愿意,否则指定后面的内容也没有用。如果您只需要数字,并且确定它将是一个或多个数字的第一个字符串,那么这就是您所需要的

如果您希望它被空格偏移,那么指定它将使它更加清晰

"\\s+(\\d+)\\s+"
可能更好

如果您需要这三个部分,则可以:

"(\\D+)(\\d+)(.*)"
编辑Allain和Jack给出的表达式建议您需要指定一些非数字的子集,以便捕获数字。如果您告诉正则表达式引擎您正在查找
\d
,那么它将忽略数字之前的所有内容。如果J或A的表达式符合您的模式,则整个匹配等于输入字符串。没有理由具体说明。如果它没有被完全忽略的话,它可能会减慢一场干净的比赛

怎么样
[^\\d]*([0-9]+[\\s]*[,]{0,1}[\\s]*[0-9]*)。
我想它会处理带有小数部分的数字。 我包括了空格和
作为可能的分隔符。
我试图从包含浮点数的字符串中提取数字,并考虑到用户在键入数字时可能会出错并包含空格。

尝试执行以下操作:

Pattern p = Pattern.compile("^.+(\\d+).+");
Matcher m = p.matcher("Testing123Testing");

if (m.find()) {
    System.out.println(m.group(1));
}
输出:

1234
789
2345
除此之外,Java类还有几个方法可以使用正则表达式,在您的例子中,代码如下:

"ab123abc".replaceFirst("\\D*(\\d*).*", "$1")

其中
\\D
是一个非数字字符。

看,您可以使用StringTokenizer来完成


由于我们将这些数字数据分成三个不同的变量,因此我们可以在代码中的任何位置使用这些数据(供进一步使用)

此函数从字符串中收集所有匹配的序列。在本例中,它从字符串中获取所有电子邮件地址

static final String EMAIL_PATTERN = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";

public List<String> getAllEmails(String message) {      
    List<String> result = null;
    Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);

    if (matcher.find()) {
        result = new ArrayList<String>();
        result.add(matcher.group());

        while (matcher.find()) {
            result.add(matcher.group());
        }
    }

    return result;
}
static final String EMAIL\u PATTERN=“[\u A-Za-z0-9-\\+]+(\\\.[u A-Za-z0-9-]+)*@”
+“[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})”;
公共列表getAllEmails(字符串消息){
列表结果=空;
Matcher Matcher=Pattern.compile(EMAIL\u Pattern).Matcher(message);
if(matcher.find()){
结果=新的ArrayList();
add(matcher.group());
while(matcher.find()){
add(matcher.group());
}
}
返回结果;
}

对于
消息=”adf@gmail.com, >>> lalala@aaa.pl“
它将创建3个元素的列表。

有时您可以使用java.lang.String中提供的simple.split(“REGEXP”)方法。例如:

String input = "first,second,third";

//To retrieve 'first' 
input.split(",")[0] 
//second
input.split(",")[1]
//third
input.split(",")[2]

如果您正在从文件中读取,那么这可以帮助您

              try{
             InputStream inputStream = (InputStream) mnpMainBean.getUploadedBulk().getInputStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
             String line;
             //Ref:03
             while ((line = br.readLine()) != null) {
                if (line.matches("[A-Z],\\d,(\\d*,){2}(\\s*\\d*\\|\\d*:)+")) {
                     String[] splitRecord = line.split(",");
                     //do something
                 }
                 else{
                     br.close();
                     //error
                     return;
                 }
             }
                br.close();

             }
         }
         catch (IOException  ioExpception){
             logger.logDebug("Exception " + ioExpception.getStackTrace());
         }
简单解 Util类中的解决方案
…现在我要去研究了。在我自己弄明白之前,让我们看看苏能不能给我一个答案-这是一个银行/投资/贸易公司的软件工程面试问题,对吗P@ennth不,一点也不接近!这是一个小型商业网站上的生产代码。。。几天前,我在摩根大通软件工程编码考试中被问到了一个几乎完全相同的问题:Pyou可以通过运行样本测试和检查Axemans的vs.a/J解决方案的性能来测试Axemans的假设。你不需要指定字符串的开头和结尾吗。否则像124xxx123xxx这样的东西会被匹配,即使它不符合他的语法?还是^和$implicit?Allain,你的也会失败。您和Jack假设非数字字符将位于数字之前。他们要么做,要么不做。在这种情况下,这些表达式都不会解析此行。我重复一下,按照规定,数字的模式就足够了。别忘了重用Patter对象。编写模式需要大量时间。同意。通常我会将模式定义为私有静态最终模式pattern=pattern.compile(“…”);但那只是我的问题。我们可以简单地使用模式p=Pattern.compile(\\d+);没有解释,这是一个糟糕的答案。在@Marquez的答案中暗示,这种方法有一个警告:匹配器是一个状态机。这还包括
p.matcher().group()
将抛出错误,因为匹配器只是创建的。在调用.find()之前,您需要实际存储匹配器并通过调用
.find()
来运行它。作为一名FP人员,我在前两个小时没有想到这一点(logging.find()总是返回true,但是.group()总是抛出…。-1。因为
+
贪婪地使用字符,
\d+
只从
“123”
捕获
“3”
。此外,在字符串文本中,您需要转义反斜杠(您的示例将无法编译)。该问题只要求第一次出现数字。请使用更多信息进行编辑。不鼓励只编码和“试试这个”答案,因为
String input = "first,second,third";

//To retrieve 'first' 
input.split(",")[0] 
//second
input.split(",")[1]
//third
input.split(",")[2]
              try{
             InputStream inputStream = (InputStream) mnpMainBean.getUploadedBulk().getInputStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
             String line;
             //Ref:03
             while ((line = br.readLine()) != null) {
                if (line.matches("[A-Z],\\d,(\\d*,){2}(\\s*\\d*\\|\\d*:)+")) {
                     String[] splitRecord = line.split(",");
                     //do something
                 }
                 else{
                     br.close();
                     //error
                     return;
                 }
             }
                br.close();

             }
         }
         catch (IOException  ioExpception){
             logger.logDebug("Exception " + ioExpception.getStackTrace());
         }
// Regexplanation:
// ^       beginning of line
// \\D+    1+ non-digit characters
// (\\d+)  1+ digit characters in a capture group
// .*      0+ any character
String regexStr = "^\\D+(\\d+).*";

// Compile the regex String into a Pattern
Pattern p = Pattern.compile(regexStr);

// Create a matcher with the input String
Matcher m = p.matcher(inputStr);

// If we find a match
if (m.find()) {
    // Get the String from the first capture group
    String someDigits = m.group(1);
    // ...do something with someDigits
}
public class MyUtil {
    private static Pattern pattern = Pattern.compile("^\\D+(\\d+).*");
    private static Matcher matcher = pattern.matcher("");

    // Assumptions: inputStr is a non-null String
    public static String extractFirstNumber(String inputStr){
        // Reset the matcher with a new input String
        matcher.reset(inputStr);

        // Check if there's a match
        if(matcher.find()){
            // Return the number (in the first capture group)
            return matcher.group(1);
        }else{
            // Return some default value, if there is no match
            return null;
        }
    }
}

...

// Use the util function and print out the result
String firstNum = MyUtil.extractFirstNumber("Testing4234Things");
System.out.println(firstNum);
Pattern p = Pattern.compile("(\\D+)(\\d+)(.*)");
Matcher m = p.matcher("this is your number:1234 thank you");
if (m.find()) {
    String someNumberStr = m.group(2);
    int someNumberInt = Integer.parseInt(someNumberStr);
}