我很难为我的字符串构造正确的正则表达式。我想要做的是从我的字符串中获取所有实体;它们以'开始和结束。这些实体可以通过数量的数字和前面的#来识别。但是,不以#开头或以'结尾的实体(在本例中是以'开头的电话号码)根本不应该匹配。
我希望有人能帮助我,或者至少告诉我,我想做的事在一次判决中是不可能的。谢谢:)
字符串:
'Blaa lablalbl balbla balb lbal '#39'blaaaaaaaa'#39' ('#39#226#8218#172#39') blaaaaaaaa #7478347878347834 blaaaa blaaaa'
RegEx:
'[#[0-9]+]*'
需要匹配:
'#39''#39''#39''#226''#8218''#172''#39'找到匹配:
'#39''#39''#39#226#8218#172#39' <- 需要拆分(如果可能的话,在同一个RegEx中)另一个RegEx:
#[0-9]+
找到匹配:
'#39''#39''#39''#226''#8218''#172''#39''#7478347878347834' <- 不应该在这里:(语言: C# .NET (4.0)
发布于 2010-09-14 13:18:05
假设您可以使用lookbehind/lookaheads,并且您的regexp支持可变长度的后置查找(仅限JGSoft/ .NET )
(?<='[#0-9]*)#\d+(?=[#0-9]*')应该有效..。对它进行了使用本网站测试,得到了以下结果:
1. #39
2. #39
3. #39
4. #226
5. #8218
6. #172
7. #39把它分解很简单:
(?<= # Start positive lookbehind group - assure that the text before the cursor
# matches the following pattern:
' # Match the literal '
[#0-9]* # Matches #, 0-9, zero or more times
) # End lookbehind...
#\d+ # Match literal #, followed by one or more digits
(?= # Start lookahead -- Ensures text after cursor matches (without advancing)
[#0-9]* # Allow #, 0-9, zero or more times
' # Match a literal '
)因此,如果前面的文本是#\d+,后面的文本是[#0-9]*',则此模式将与[#0-9]*'匹配。
发布于 2010-09-14 13:05:38
您不能在一个正则表达式中这样做,您需要两个:
首先,取单引号之间的所有匹配:
'[\d#]+'然后,在所有的比赛中,做这样的事情:
#\d+因此,您将得到类似的结果(在C#中):
foreach(var m in Regex.Matches(inputString, @"'[\d#]+'"))
{
foreach(var m2 in Regex.Matches(m.Value, @"#\d+"))
{
yield return m2.Value;
}
}发布于 2010-09-14 13:20:55
由于您没有指定语言,下面是perl的解决方案:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $s = qq!Blaa lablalbl balbla balb lbal '#39'blaaaaaaaa'#39' ('#39#226#8218#172#39') blaaaaaaaa #7478347878347834 blaaaa blaaaa!;
my @n = $s =~ /(?<=['#\d])(#\d+)(?=[#'\d])/g;
print Dumper(\@n);产出:
$VAR1 = [
'#39',
'#39',
'#39',
'#226',
'#8218',
'#172',
'#39'
];https://stackoverflow.com/questions/3709091
复制相似问题