问题描述
我正在尝试扫描给定字符串中的数字.数字不能在v/v./vol/vol."之后,也不能在括号内.这是我所拥有的:
NSString *regex = @"(?i)(?<!v|vol|vol\\.|v\\.)\\d{1,4}(?![\\(]{0}.*\\))";NSLog(@"Result: %@", [@"test test test 4334 test test" stringByMatching:regex]);NSLog(@"Result: %@", [@"test test test(4334) test test" stringByMatching:regex]);NSLog(@"Result: %@", [@"test test test(vol.4334) test test" stringByMatching:regex]);
令人气愤的是,这行不通.我的正则表达式可以分为四部分:
(?i)
- 使正则表达式不区分大小写
(?<!v|vol|vol\\.|v\\.)
- v/v./vol/vol 的否定后视断言.
\\d{1,4}
- 我要查找的号码,1-4 位数字.
(?![\\(]{0}.*\\))
- 否定前瞻断言:数字不能在 ) 之前,除非在它之前有 ( .>
令人抓狂的是,如果我去掉后视断言,它就起作用了.这里有什么问题?我正在使用 RegexKitLite,它使用 ICU 正则表达式语法.
您的 negative lookbehind
位置不正确.Lookbehind 不修改输入位置,你的 negative lookbehind
应该在你的 \d{1,4}
表达式之后:
(?i)\\d{1,4}(?<!v|vol|vol\\.|v\\.)(?![\\(]{0}.*\\))
或者,只需使用 negative lookahead
来实现相同的目的:
(?i)(?!v|vol|vol\\.|v\\.)\\d{1,4}(?![\\(]{0}.*\\))
I'm trying to scan a given string for a number. The number cannot be after "v/v./vol/vol.", and cannot be inside parentheses. Here's what I have:
NSString *regex = @"(?i)(?<!v|vol|vol\\.|v\\.)\\d{1,4}(?![\\(]{0}.*\\))";
NSLog(@"Result: %@", [@"test test test 4334 test test" stringByMatching:regex]);
NSLog(@"Result: %@", [@"test test test(4334) test test" stringByMatching:regex]);
NSLog(@"Result: %@", [@"test test test(vol.4334) test test" stringByMatching:regex]);
Infuriatingly, this does not work. My regex can be separated into four parts:
(?i)
- make regex case insensitive
(?<!v|vol|vol\\.|v\\.)
- negative look-behind assertion for v/v./vol/vol.
\\d{1,4}
- the number I'm looking for, 1-4 digits.
(?![\\(]{0}.*\\))
- negative look-ahead assertion: number cannot be preceding a ), unless there's a ( before it.
Maddeningly, if I take out the look-behind assertion, it works. What's the issue here? I'm using RegexKitLite, which uses the ICU regex syntax.
Your negative lookbehind
is positioned incorrectly. Lookbehind's do not modify the input position, your negative lookbehind
should come after your \d{1,4}
expression:
(?i)\\d{1,4}(?<!v|vol|vol\\.|v\\.)(?![\\(]{0}.*\\))
Alternatively, just use a negative lookahead
to accomplish the same purpose:
(?i)(?!v|vol|vol\\.|v\\.)\\d{1,4}(?![\\(]{0}.*\\))
这篇关于使用 ICU 正则表达式查找不在括号内的数字的正则表达式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!