3

I have the following Regex

console.log("Test #words 100-200-300".toLowerCase().match(/(?:\B#)?\w+/g))

From the above you can see it is splitting "100-200-300". I want it to ignore "-" and keep the word in full as below:

--> ["test", "#words", "100-200-300"]

I need the Regex to keep the same rules, with the addition of not splitting words connected with "-"

7
  • 1
    You could repeat matching - and \w+ like (?:\B#)?\w+(?:-\w+)* or without the \B like #?\w+(?:-\w+)* regex101.com/r/YRg5My/1 Commented Oct 1, 2019 at 16:19
  • 2
    Is regex the right solution? Would it be better to use javascript to split on a space character: str.split(" ")? What do you do in case of words_separated_by_underscores? Commented Oct 1, 2019 at 16:19
  • I am not sure what the regex does entirely, It is a line of code we are using in an indexing script. It is causing a fault since it splits on "-" i don't want to change what it does just stop it splitting on "-" Commented Oct 1, 2019 at 16:21
  • @Thefourthbird could you show me how the entire Regex should look I don't understand what you are suggesting - Thanks. Commented Oct 1, 2019 at 16:23
  • @MartinWebb You might shorten the code and omit .toLowerCase() as \w also matches that. Try console.log("Test #words 100-200-300".match(/#?\w+(?:-\w+)*/g)); See rextester.com/RSVR49477 Commented Oct 1, 2019 at 16:27

1 Answer 1

4

For your current example, you could match an optional #, 1+ word chars and repeat 0+ times a part that matches a # and 1+ word chars again.

#?\w+(?:-\w+)*
  • #? Optional #
  • \w+ 1+ word characters
  • (?:-\w+)* Repeat as a group 0+ times matching - and 1+ word chars

Regex demo

console.log("Test #words 100-200-300".toLowerCase().match(/#?\w+(?:-\w+)*/g));

About the \B anchor (following text taken from the link)

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

If you do want to use that anchor, see for example some difference in matches with \B and without \B

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

1 Comment

Perfect. Thank you.

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.