Preg_match PHP for java translation

I am having problems converting php pregmatch to java. I thought everything was correct, but it does not seem to work. 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 is:

 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: DBA40365-7346-4DB4-A2CF-52ECA8C64091-0

Using the System.outs series, I get b = false.

+4
source share
2 answers

To implement the function, as 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 like:

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

You do not need a bracket in pattern because it just creates a matching group that you are not using. If you need access to backlinks, you will need a bracket for more advanced regex code using the pattern and Matcher classes.

+7
source

You can just use String.matches()

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

Source: https://habr.com/ru/post/1441299/


All Articles