这个Objective-C正则表达式出了什么问题?

时间:2021-10-29 03:26:04

I'm trying to detect any words between asterisks:

我试图检测星号之间的任何单词:

NSString *questionString = @"hello *world*";
NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:questionString]; //should turn the word "world" blue

    NSRange range = [questionString rangeOfString:@"\\b\\*(.+?)\\*\\b" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
    if (range.location != NSNotFound) {
        DLog(@"found a word within asterisks - this never happens");
        [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
    }

But I never get a positive result. What's wrong with the regex?

但我从来没有得到积极的结果。正则表达式有什么问题?

1 个解决方案

#1


3  

@"\\B\\*([^*]+)\\*\\B"

should achieve what you expect.

应该达到你的期望。

You have to use \B in place of \b for word boundaries, as per Difference between \b and \B in regex.

您必须使用\ B代替\ b作为单词边界,根据正则表达式中\ b和\ B之间的差异。

Finally, using [^*]+ matches each pair of asterisks, instead of the outermost only.

最后,使用[^ *] +匹配每对星号,而不是最外面的星号。

For instance, in the string

例如,在字符串中

Hello *world* how *are* you

你好*世界*如何*是*你

it will correctly match world and are, instead of world how are.

它将正确匹配世界,而不是世界如何。

Another way for achieving the same is using ? which will make the + non-greedy.

实现同样的另一种方法是使用?这将使+非贪婪。

@"\\B\\*(.+?)\\*\\B"

Also it's worth noting that rangeOfString:options returns the range of the first match, whereas if you are interested in all the matches you have to use build a NSRegularExpression instance with that pattern and use its matchesInString:options:range: method.

另外值得注意的是rangeOfString:options返回第一个匹配的范围,而如果您对所有匹配感兴趣,则必须使用该模式构建NSRegularExpression实例并使用其matchesInString:options:range:方法。

#1


3  

@"\\B\\*([^*]+)\\*\\B"

should achieve what you expect.

应该达到你的期望。

You have to use \B in place of \b for word boundaries, as per Difference between \b and \B in regex.

您必须使用\ B代替\ b作为单词边界,根据正则表达式中\ b和\ B之间的差异。

Finally, using [^*]+ matches each pair of asterisks, instead of the outermost only.

最后,使用[^ *] +匹配每对星号,而不是最外面的星号。

For instance, in the string

例如,在字符串中

Hello *world* how *are* you

你好*世界*如何*是*你

it will correctly match world and are, instead of world how are.

它将正确匹配世界,而不是世界如何。

Another way for achieving the same is using ? which will make the + non-greedy.

实现同样的另一种方法是使用?这将使+非贪婪。

@"\\B\\*(.+?)\\*\\B"

Also it's worth noting that rangeOfString:options returns the range of the first match, whereas if you are interested in all the matches you have to use build a NSRegularExpression instance with that pattern and use its matchesInString:options:range: method.

另外值得注意的是rangeOfString:options返回第一个匹配的范围,而如果您对所有匹配感兴趣,则必须使用该模式构建NSRegularExpression实例并使用其matchesInString:options:range:方法。