用于匹配斜体文本格式的预定义规则的正则表达式

Regex for matching predefined rules for italic text formatting

我正在尝试编写一个正则表达式来匹配用户输入,它将使用 markdown 转换为斜体格式。

我需要在字符串中找到以下模式:一个星号后跟任何一种非空白字符,并以任何一种非空白字符后跟一个星号结尾。

所以基本上:substring *substring substring substring* substring 应该吐出 *substring substring substring*

到目前为止,我只想到了 /\*(?:(?!\*).)+\*/,它匹配两个星号之间的所有内容,但它没有考虑星号之间的子字符串是以空格开头还是以空格结尾——这是不应该的。

感谢您的意见! :)

使用

\*(?![*\s])(?:[^*]*[^*\s])?\*

参见regex proof

解释

--------------------------------------------------------------------------------
  \*                       '*'
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    [*\s]                    any character of: '*', whitespace (\n,
                             \r, \t, \f, and " ")
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    [^*]*                    any character except: '*' (0 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    [^*\s]                   any character except: '*', whitespace
                             (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
  )?                       end of grouping
--------------------------------------------------------------------------------
  \*                       '*'