Java/Regex: Negate the same character repeated twice:

Pepria :

If I have the following string:

--l=Richmond-Hill, NYC --m=5-day --d=hourly

I want to match the groups:

--l=Richmond-Hill, NYC

--m=5-day

--d=hourly

I came up with the following regex:

(^--[a-zA-Z]=[^-]*)

This works when the value after the equal sign doesn't have a dash. Basically, how do I negate a double dash ?

Emma :

My guess is that maybe you wish to design some expression similar to:

--[a-zA-Z]=.*?(?=--|$)

Demo

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class re{
    public static void main(String[] args){

        final String regex = "--[a-zA-Z]=.*?(?=--|$)";
        final String string = "--l=Richmond-Hill, NYC --m=5-day --d=hourly\n"
             + "--l=Richmond-Hill, NYC\n"
             + "--m=5-day\n"
             + "--d=hourly";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}

Output

Full match: --l=Richmond-Hill, NYC 
Full match: --m=5-day 
Full match: --d=hourly
Full match: --l=Richmond-Hill, NYC
Full match: --m=5-day
Full match: --d=hourly

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141702&siteId=1