3

I am having some trouble converting a php pregmatch to java. I thought I had it all correct but it doesn't seem to be working. Here is the code:

Original PHP:

/* Pattern for 44 Character UUID */
$pattern = "([0-9A-F\-]{44})";
if (preg_match($pattern,$content)){
                /*DO ACTION*/
            }

My Java code:

final String pattern = "([0-9A-F\\-]{44})";
    public static boolean pregMatch(String pattern, String content) {
            Pattern p = Pattern.compile(pattern);
            Matcher m = p.matcher(content);
            boolean b = m.matches();
            return b;
        }
if (pregMatch(pattern, line)) {
                        //DO ACTION
                    }

So my test input is: DBA40365-7346-4DB4-A2CF-52ECA8C64091-0

Using a series of System.outs I get that b = false.

2 Answers 2

8

To implement a function as you did in your code:

final String pattern = "[0-9A-F\\-]{44}";
public static boolean pregMatch(String pattern, String content) {
    return content.matches(pattern);
}

And then you can call it as:

if (pregMatch(pattern, line)) {
    //DO ACTION
}

You don't need the parenthesis in your pattern because that just creates a match group, which you are not using. If you need access to back references, you would need the parenthesis an a more advanced regex code using Pattern and Matcher classes.

Sign up to request clarification or add additional context in comments.

2 Comments

I can't tell if the lines I'm trying to match is the issue or not. Some examples are: B3AF08DE-7F02-450B-A316-94AB10603956-0 ||| 83202015-E001-422C-9792-1D298893A289-0 ||| DBA40365-7346-4DB4-A2CF-52ECA8C64091-0 Is there something wrong with these lines that they fail or perhaps something else wrong in my code?
Those strings are 38 characters long, and your regex is trying to match 44 characters with {44}. Use the regex pattner [0-9A-F\\-]{38} and it will match each one of those values. If you want to match strings 38 to 44 characters long, use [0-9A-F\\-]{38,44}
6

You could just use String.matches()

if (line.matches("[0-9A-F-]{44}")) {
  // do action
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.