5

How to convert regex java in regex javascript

I have for example the text : #hello some text #Home

My Java regex is

String regex = "[#]+[A-Za-z0-9-_]+\\b";
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");

the result is #hello and #Home

My Javascript code is :

var myRegExp = new RegExp("[#]+[A-Za-z0-9-_]+\\b");
var tagMatcher = text.match(myRegExp);

but the result is :

#hello

How can I solve the problem?

Where is my error?

4
  • @Zenoo — No. It's a string being passed to a regex compiler function. The double slash is needed in JS for the same reason it is needed in Java.
    – Quentin
    Mar 22, 2018 at 16:10
  • you did not tell it to match multiple. developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… Mar 22, 2018 at 16:11
  • 1
    As an aside, you can express this much more succinctly in both Java and JavaScript by using # instead of [#] and [\w-] instead of [A-Za-z0-9-_]. Mar 22, 2018 at 16:26
  • the problem in this case is : if insert #Ho#me the result is [ #Ho #me ] the correct result is: or only tag #Ho and #me is simple text or no tag
    – Matteo
    Mar 23, 2018 at 11:34

1 Answer 1

3

Missing global flag g to get the whole set of matches.

var text = "#hello some text #Home";
var myRegExp = new RegExp("[#]+[A-Za-z0-9-_]+\\b", "g");
var tagMatcher = text.match(myRegExp);

console.log(tagMatcher)

Like @JordanRunning mentioned, you can use Regex literal as follow, as well as a shorter approach:

var text = "#hello some text #Home";
var tagMatcher = text.match(/#+[\w-]+\b/g);

console.log(tagMatcher)

Advanced searching with flags

Regular expressions have five optional flags that allow for global and case insensitive searching. These flags can be used separately or together in any order, and are included as part of the regular expression.

4
  • 1
    It would probably be more idiomatic to express this as a RegExp literal: /[#]-[A-Za-z0-9_]+\b/g or, more succinctly, /#-\w+\b/g. Mar 22, 2018 at 16:22
  • @JordanRunning yes, I agree. I will put that in this answer.
    – Ele
    Mar 22, 2018 at 16:24
  • 1
    Oops, that wasn't quite right. OP needs - in the character class, so it would be /#-[\w-]+\b/g. Mar 22, 2018 at 16:26
  • @Ele the problem in this case is : if insert #Ho#me the result is [ #Ho #me ] the correct result is: or only tag #Ho and #me is simple text or no tag
    – Matteo
    Mar 23, 2018 at 11:21

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.