2010-10-28 96 views
7

想象一下,我们有一个包含子字符串'cat'和'dog'以及其他随机字符的长字符串,例如。字符串模式匹配问题

cat x dog cat x cat x dog x dog x cat x dog x cat 

这里'x'表示任何随机的字符序列(但不是'猫'或'狗')。

我想要做的是找到每个'猫',其后是任何字符,除了'狗',然后是'猫'。我想在每种情况下删除第一个“猫”的实例。

在这种情况下,我会想删除括号[猫]因为没有“狗”后,之前的下一个“猫”:

cat x dog x cat x dog x dog x cat x dog x cat 

cat x dog [cat] x cat x dog x dog x cat x dog x cat 

就结了

这怎么办?

我想以某种方式使用像(N)(?=(n))的正则表达式的作为VonC推荐 here

(cat)(?=(.*cat)) 

以匹配字符串中的所有对 '猫' 的。但我仍然不确定如何使用它来删除在“猫”之前没有跟随“狗”的每只猫。


我正在处理的真正问题是在Java中。但我真的只是寻找一个通用的伪代码/正则表达式解决方案。

+0

嗨。知道你在用什么语言工作会很有用。 – 2010-10-28 16:43:02

+0

@klausbyskov:你确定要编辑吗?下面的两句话和这个例子似乎表明,“跟随”的确是他的意思。 – 2010-10-28 16:51:12

+0

我的意思是'跟着'没有先行! – nodmonkey 2010-10-28 16:56:26

回答

2

是否有任何特殊的原因,你想这样做只有一个RE呼叫?我不确定这是否真的可能在一个RE中。

如果我必须这样做,我可能会两次通过。首先在字符串中标记每个“猫”和“狗”的实例,然后编写一些代码来确定哪些猫需要删除,并在另一个通道中执行该操作。

伪代码如下:

// Find all the cats and dogs 
int[] catLocations = string.findIndex(/cat/); 
int[] dogLocations = string.findIndex(/dog/); 
int [] idsToRemove = doLogic(catLocations, dogLocations); 

// Remove each identified cat, from the end to the front 
for (int id : idsToRemove.reverse()) 
    string.removeSubstring(id, "cat".length());