2

I have a a regex in Javascript that works great: /:([\w]+):/g

I am working on converting my javascript app to java, and I know to escape the \ using \ i.e. /:([\\w]+):/g, yet my tests are still returning no match for the string "hello :testsmilie: how are you?"

    Pattern smiliePattern = Pattern.compile("/:([\\w]+):/g");
    Matcher m = smiliePattern.matcher(message);
    if(m.find()) {
        System.println(m.group(0));
     }

In javascript it returns ":testsmilie:" just fine, so i'm not sure what the difference is. Any help would be much appreciated!

1
  • Java uses a different set of rules than JavaScript, much like PHP vs JavaScript, JS doesnt allow look behinds and other sorts , google the differences Commented Nov 1, 2018 at 15:06

2 Answers 2

5

Your regex in java can just be :

Pattern.compile(":[^:]+:")

Which match : followed by one or more no two dots : followed by :

Or if you want to use \w you can use :

Pattern.compile(":\\w+:")

If you note you don't need parenthesis of group (), so to get the result you can just use :

System.out.println(m.group());
Sign up to request clarification or add additional context in comments.

Comments

2

You should learn how is made a Javascript regex, because the / are the delimiters of the real regex, and g is a modifier for global

In Java the equivalent is: :([\\w]+):, and no need of global flag as you just need to call multiple times .find() to get all the matches


You should take a look at regex101 which is a good website to test regex

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.