简体   繁体   English

使用正则表达式在Java中查找子字符串

[英]Using regex to find substring in Java

I am trying to pull two strings (which represent integers i where -999999 <= i <= 999999) out of the string 'left.' 我试图从字符串'left'中拉出两个字符串(表示整数,其中-999999 <= i <= 999999)。 There will always be exactly two strings representing two integers. 总会有两个字符串代表两个整数。 Also I want the regex to match {"-1", "2"} for "-1-2", not {"-1", "-2"}. 另外,我希望正则表达式匹配{“-1”,“2”}为“-1-2”,而不是{“ - 1”,“ - 2”}。 I've been going through the tutorials on http://www.regular-expressions.info and the stackoverflow regex page for going on four hours now. 我已经浏览了http://www.regular-expressions.info上的教程和stackoverflow正则表达式页面,现在进行了四个小时。 I am testing my expressions in a Java program. 我正在Java程序中测试我的表达式。 Here's what I've got 这就是我所拥有的

String left = "-123--4567";
    Pattern pattern = Pattern.compile("-?[0-9]{1,6}");
    Matcher matcher = pattern.matcher(left);
        arg1 = matcher.group(1);
        arg2 = matcher.group(2);
    System.out.println("arg1: " + arg1 + " arg2: " + arg2);

This code should produce 这段代码应该产生

arg1: -123 arg2: -4567

Here's a self-contained example of what you're probably trying to do: 以下是您可能尝试执行的操作的自包含示例:

String[] examples = {
    "-123--4567",
    "123-4567",
    "-123-4567",
    "123--4567"
};
//                           ┌ group 1:
//                           |┌ zero or one "-"
//                           || ┌ any number of digits (at least one)
//                           || |    ┌ zero or one "-" as separator    
//                           || |    | ┌ group 2
//                           || |    | |┌ zero or one "-"
//                           || |    | || ┌ any number of digits (at least one)
Pattern p = Pattern.compile("(-?\\d+)-?(-?\\d+)");
// iterating over examples
for (String s: examples) {
    // matching
    Matcher m = p.matcher(s);
    // iterating over matches (only 1 per example here)
    while (m.find()) {
        // printing out group1 --> group 2 back references
        System.out.printf("%s --> %s%n", m.group(1), m.group(2));
    }
}

Output 产量

-123 --> -4567
123 --> 4567
-123 --> 4567
123 --> -4567

You can use this regex: 你可以使用这个正则表达式:

(-?[0-9]{1,6})-?

And grab capture group #1 并抓住捕获组#1

RegEx Demo RegEx演示

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

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