1

I have the following regex: /\*\*[A-z0-9]+\*\*/g It's supposed to match words with double * around them, like so: **this whole sentence should match**

However it's not matching the spaces. So **this is a word** (this would not be matched), however **word** would be matched (without spaces).

Should match:

  • **this sentence is bold**
  • **this should also match**
  • **should**
James111
  • 15,378
  • 15
  • 78
  • 121
  • 3
    See https://stackoverflow.com/questions/13283470/regex-for-allowing-alphanumeric-and-space. BTW, `A-z` defines a range that also includes some chars other than just ASCII letters. Use `/\*\*[a-z0-9\s]+\*\*/gi` – Wiktor Stribiżew Jan 03 '18 at 07:47
  • Perfect @WiktorStribiżew – James111 Jan 03 '18 at 07:49

3 Answers3

1

The expression you wrote will find a match when the subject starts with two *s (star-star) characters and any character in your caracter set [A-z0-9] (any ASCII character from A to Z or a - z or any digit like 1234567890) and ends with two *s (star start) characters. What is missing here is including a space in your character set. By including "\ " you are specifying that a space litteral is also a valid character in your expression.

\*\*[A-z0-9\ ]+\*\*

Please note that this will match on any number of spaces so words like **john doe ** will still be considered valid. If you only want to match on one space you can consider:

\*\*(?:[A-z0-9](?:[\ ]?))+\*\*
Desmond Nzuza
  • 130
  • 1
  • 11
0

Adding a space in character class will solve the problem.

/\*\*[A-z0-9 ]+\*\*/g
DarkBee
  • 16,592
  • 6
  • 46
  • 58
0

The solution from Wiktor Stribizew does also include tabs and new lines. If you would like to only include spaces a solution as

/\*\*[a-z0-9 ]+\*\*/gi

will do. The \s is replaced with a single space. Since the plus sign + is added, multiple spaces will alse be matched.

Sebastian Proske
  • 8,255
  • 2
  • 28
  • 37
Jelle
  • 1
  • 1