【问题标题】:Regex for matching predefined rules for italic text formatting用于匹配斜体文本格式的预定义规则的正则表达式
【发布时间】:2021-07-16 15:10:07
【问题描述】:

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

在字符串中,我需要找到以下模式:星号后跟任何类型的非空白字符,并以任何类型的非空白字符后跟星号结束。

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

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

感谢您的意见! :)

【问题讨论】:

  • 试试/\*(?!\s).*?\*(?<!\s\*)/
  • @isaactfa 但是\S 匹配一个* 字符,而/\*\S.*?\S\*/ 不能匹配一个星号之间只有一个字符的*.* 字符串。
  • @WiktorStribiżew 好点!真的应该是/\*[^\s\*](?:.*?[^\s\*])?\*/
  • 是的,或者/\*(?![\s*]).*?\*(?<![\s*]\*)/ 然后
  • \*[^*\s](?:[^*]*[^*\s])?\* 会工作

标签: regex italic


【解决方案1】:

使用

\*(?![*\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
--------------------------------------------------------------------------------
  \*                       '*'

【讨论】:

  • 非常感谢您的解释,效果很好。我还做了一个补充 - 在它前面添加了(?<!\*),所以如果我们在开头有两个星号,则模式不匹配:(?<!\*)\*(?![*\s])(?:[^*]*[^*\s])?\*,这很有用,因为我想将降价匹配为粗体,即@ 987654326@
猜你喜欢
  • 2015-02-24
  • 2018-07-13
  • 2011-06-19
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-07
相关资源
最近更新 更多