简体   繁体   English

仅当两者之间存在某些文本时,正则表达式才匹配星号

[英]Regex to match asterisk only if some text is present in between

I have a regex pattern that detects the whole pattern, that is, asterisks along with the text in between.我有一个正则表达式模式,可以检测整个模式,即星号以及中间的文本。

Pattern: (\*|__)(.*?)\1模式: (\*|__)(.*?)\1

I want it to only match the asterisks, when the words are present in between.我希望它只匹配星号,当单词出现在两者之间时。 Example:例子:

*This is one* This is some other text *New word* Another text another* and there is some more text
  • Asterisks of This is one should be detected; This is one的星号应该被检测到;
  • Asterisks of New word should be detected;应检测New word的星号;
  • Last asterisk shouldn't be detected, as it doesn't have any closing one.不应检测到最后一个星号,因为它没有任何结束星号。

I tried several ways, but couldn't find a way, in which the middle words are not detected and only the asterisk.我尝试了几种方法,但找不到一种方法,其中没有检测到中间词,只有星号。

Programming Language: Typescript (Angular)编程语言:Typescript(角)

Example 2:示例 2:

*Project Name:* This is some other text *New word* Another text another and there is some more text

You can use您可以使用

/(\*|__)(?!\s)(.+?)(?<!\s)\1/g

See the regex demo .请参阅正则表达式演示 Since you want to actually enclose * with tags, you may use the <i>$2</i> replacement pattern where $2 is a backreference to the Group 2 value.由于您实际上想用标签将*括起来,您可以使用<i>$2</i>替换模式,其中$2是对 Group 2 值的反向引用。

Details :详情

  • (\*|__) - Group 1: * or __ (\*|__) - 第 1 组: *__
  • (?!\s) - no whitespace is allowed immediately to the right of the current location (?!\s) - 当前位置右侧不允许有空格
  • (.+?) - Group 2: any one or more chars other than line break chars as few as possible (.+?) - 第 2 组:除换行符之外的任何一个或多个字符,尽可能少
  • (?<!\s) - no whitespace is allowed immediately on the left of the current location (?<!\s) - 当前位置左侧不允许有空格
  • \1 - the same value as in Group 1 ( * or __ ). \1 - 与第 1 组( *__ )中的值相同。

See the JavaScript demo:请参阅 JavaScript 演示:

 let text = '*This is one* This is some other text *New word* Another text another* and there is some more text **'; text = text.replace(/(\*|__)(?.\s)(?+?)(,<;\s)\1/g. '<i>$2</i>'); console.log(text);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM