6

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. Commented Mar 22, 2018 at 16:10
  • you did not tell it to match multiple. developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… Commented 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-_]. Commented 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 Commented 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.

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

4 Comments

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.
@JordanRunning yes, I agree. I will put that in this answer.
Oops, that wasn't quite right. OP needs - in the character class, so it would be /#-[\w-]+\b/g.
@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

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.