简体   繁体   English

Java正则表达式提取带有边界和可选空间的数字

[英]java regex extract numbers with boundary and optional space

I am trying to extract 12 and 15. 我正在尝试提取12和15。

AB CD 12 ABC/15 DEF
.*\bAB CD\b\s?(\d+)\s?\bABC\b[/](\d+)\s?\bDEF\b

It is not working as i am not sure how to match exact words. 它不起作用,因为我不确定如何匹配确切的单词。 I am trying to match exact words using boundary and it seems to be creating a problem. 我正在尝试使用边界匹配确切的单词,这似乎造成了问题。

I tried 我试过了

.*\\bAB CD\\b\\s?(\\d+)\\s?\\bABC\\b[/](\\d+)\\s?\\bDEF\\b
.*\\bAB CD\\b\\s*(\\d+)\\s*\\bABC\\b[/](\\d+)\\s*\\bDEF\\b
.*\\bAB CD\\b[\\s]?(\\d+)[\\s]?\\bABC\\b[/](\\d+)[\\s]?\\bDEF\\b
.*\\bAB CD\\b[\\s]*(\\d+)[\\s]*\\bABC\\b[/](\\d+)[\\s]*\\bDEF\\b

thanks. 谢谢。

Besides the expression being a little redundant, you must be doing something wrong, as your very first expression works: 除了表达式有点多余之外,您还必须做错什么,因为第一个表达式可以工作:

import java.util.*;
import java.util.regex.*;
import java.lang.*;
 
class Main {
    public static void main (String[] args) throws java.lang.Exception {
        
        String currentLine = "AB CD 12 ABC/15 DEF";
        System.out.println("Current Line: "+ currentLine);
        Pattern p = Pattern.compile(".*\\bAB CD\\b\\s?(\\d+)\\s?\\bABC\\b[/](\\d+)\\s?\\bDEF\\b");
        Matcher m = p.matcher(currentLine);
        while (m.find()) {
            System.out.println("Matched: "+m.group(1));
            System.out.println("Matched: "+m.group(2));
        }
        
    }
}

And a demo link to prove: http://ideone.com/0tXFNu 以及一个演示链接来证明: http : //ideone.com/0tXFNu

Output: 输出:

Current Line: AB CD 12 ABC/15 DEF
Matched: 12
Matched: 15

So make sure you use m.group(NUMBER) to access each of the matched values. 因此,请确保使用m.group(NUMBER)来访问每个匹配的值。

您可以使用此:

"AB\\s*CD\\s*(\\d+)\\s*ABC/(\\d+)\\s*DEF"

What you want is just extract digits out of string, try following code: 您想要的只是从字符串中提取数字,请尝试以下代码:

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("AB CD 12 ABC/15 DEF");
while (m.find()) {
    System.out.println(m.group());
}

If you want string match exactly except digits: 如果您希望字符串完全匹配(数字除外):

Pattern p = Pattern.compile("AB\\s+CD\\s+(\\d+)\\s+ABC/(\\d+)\\s*DEF");
Matcher m = p.matcher("AB CD 12 ABC/15 DEF");
if (m.find()) {
    System.out.println(m.group(1));
    System.out.println(m.group(2));
}
.*\bAB CD\b\s?(\d+)\s?\bABC\b[/](\d+)\s?\bDEF\b
                           ^^^        ^^ you dont need these \b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM