nod*_*key 7 regex string pattern-matching
想象一下,我们有一个包含子串'cat'和'dog'以及其他随机字符的长字符串,例如.
cat x dog cat x cat x dog x dog x cat x dog x cat
Run Code Online (Sandbox Code Playgroud)
这里'x'代表任何随机的字符序列(但不是'cat'或'dog').
我想要做的是找到除"狗"之外的所有字符后面的每个"猫",然后是"猫".我想在每种情况下删除第一个'cat'实例.
在这种情况下,我想删除括号[cat],因为在下一个'cat'之前没有'dog':
cat x dog [cat] x cat x dog x dog x cat x dog x cat
Run Code Online (Sandbox Code Playgroud)
最终得到:
cat x dog x cat x dog x dog x cat x dog x cat
Run Code Online (Sandbox Code Playgroud)
如何才能做到这一点?
我想以某种方式使用类似(N)(?=(n))的正则表达式作为VonC推荐 这里
(cat)(?=(.*cat))
Run Code Online (Sandbox Code Playgroud)
匹配字符串中的所有'cat'对.但是我仍然不确定如何使用它来移除每只在'cat'之前没有跟随'dog'的猫.
我正在处理的真正问题是Java.但我真的只是在寻找一般的伪代码/正则表达式解决方案.
您想通过一次 RE 调用来完成此操作是否有任何特殊原因?我不确定这在 RE 中是否真的可行。
如果我必须这样做,我可能会分两次进行。首先标记字符串中“cat”和“dog”的每个实例,然后编写一些代码来识别需要删除哪些猫,并在另一遍中执行此操作。
伪代码如下:
// 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());
Run Code Online (Sandbox Code Playgroud)