2013-06-19 25 views
0

我试图用正则表达式来匹配前面有特定单词的文本(在这种情况下,单词“幻灯片”和“标题”)。我一直试图使用隐藏断言并将它们嵌套在一起,但它似乎没有工作。另一个问题是,我用来匹配的“幻灯片”和“标题”单词之间还有一些其他文字。如果在两者之间有文本,我如何嵌套后视声明?

我已经试过:

(?<=slide(?<=title\\s=\\s)).*(?=\\\") 
(?<=title\\s=\\s(?<=slide)).*(?=\\\") 

任何建议,如何做到这一点?额外的斜杠是为了逃避;我在Objective-C中使用了这个,但是我不知道这很重要。

我刮了更好的上下文中的JSON的一部分(我在寻找“称号”,在每一张幻灯片后,拿到冠军):

slide =     { 
       createdAt = "2013-06-18T20:06:50Z"; 
       description = "<p>Due to the amount of attention paid to each organization's top prospects and early-round draft picks, many of the game's underrated prospects are perpetually obscured. Most of the time, these prospects are younger players who are housed in the low minors and still require considerable physical projection. At the same time, there are countless prospects on the older side of the age curve who have dipped off the radar due to injury.</p><p>Here's a look at one \"hidden gem\" from each organization who could make a push for the major leagues in the coming years.</p>"; 
       embedCode = ""; 
       externalId = "<null>"; 
       id = 3219926; 
       photoHasCropExact = 1; 
       photoHasCropNorth = 0; 
       primaryPhoto =      { 
        url = "http://img.bleacherreport.net/img/slides/photos/003/219/926/hi-res-5382332_crop_north.jpg"; 
       }; 
       title = "Each MLB Team's 'Hidden Gem' Prospect Fans May Not Know About"; 
       updatedAt = "2013-06-18T22:26:30Z"; 
       url = "<null>"; 
+1

你想用正则表达式解析JSON吗?适当的JSON解析器(如NSJSONSerialization)将是更好的解决方案。顺便说一句。你在问题中显示的不是JSON。 - 也许你可以更好地解释你*真正想达到的目标。 –

+0

修复它非常感谢。刚刚结束了使用NSJSONSerialization,而不是感谢帮助。 – ARomano

回答

1

我就这一个与@MartinR同意,但回答正则表达式的问题,这是因为你确实指定了一个不可能的条件。你意思

(?<=(?<=title\\s=\\s)slide).*(?=\\\") 
(?<=(?<=slide)title\\s=\\s).*(?=\\\") 

想知道为什么,考虑下面的正则表达式:

(?<=foo(?<=bar)). 

您正在寻找由“富” 通过“栏”前面前面的字符。当然,为什么“foo”和“bar”永远不会相同,这种情况永远不会匹配。如果你想“栏”先“富”,那么你一定要做到这样:

(?<=(?<=bar)foo). 

另外,请记住,在大多数情况下,正则表达式引擎不支持可变宽度lookbehinds。你的例子只包含固定宽度的向后看,但如果你的实际实现更复杂,这可能是你的正则表达式无法工作的另一个原因。

+0

非常有帮助的解释非常感谢! – ARomano