我正在编写一个程序来检测文本中的降价强调语法。例如,用**
括起来的粗体语法和用*
括起来的斜体语法。
我有以下正则表达式模式:
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"(\\*{1,2}).+?(\\*{1,2})"
options:NSRegularExpressionDotMatchesLineSeparators
error:NULL];
但是,此模式还会检测配对错误的模式。例如,匹配* this is a **sample** text
将返回* this is a **
而不是**sample**
。
如何解决问题?
答案 0 :(得分:2)
你可以使用这种模式的后引用:
(\*{1,2}).+?\1
这意味着无论在第一组(单个或双星号)中捕获的内容,都必须稍后重复为\1
。
例如:
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"(\\*{1,2}).+?\\1"
options:NSRegularExpressionDotMatchesLineSeparators
error:NULL];