使用正则表达式查找不在两个字符之间的文本 [英] Use regex to find text NOT between two characters

查看:45
本文介绍了使用正则表达式查找不在两个字符之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单词字符串,其中每个单词由换行符分隔.我使用 RegEx 替换在常见前缀和后缀周围插入 '{' 和 '}' 字符.结果如下:

I have a single string of words, in which each word is separated by a newline character. I've used RegEx replacements to insert '{' and '}' characters around common prefixes and suffixes. The result looks like this:

{con}descens{ion}
lumberjack
tim{ing}
{tox}{icity}
fish
{dis}pel

我想弄清楚的是如何对这个字符串执行 RegEx 替换,它只会匹配 'not 之间的文本/strong>' 和 '}' 字符.我有进一步的替换,每次我都会在匹配项周围放置{"和}"字符;我只是不想在执行新替换时匹配以前的替换(或其中的部分).例如,我知道如何匹配not '{'",但我不知道如何匹配not between '{' and '}'"

What I'm trying to figure out is how I can perform a RegEx replace on this string that will only match text not between the '{' and '}' characters. I have further replacements to make, and each time I do, I'll be placing the '{' and '}' characters around the matches; I just don't wan't previous replacements (or pieces thereof) to be matched when performing new replacements. I know how to match "not '{'", for example, but I don't know how to match "not between '{' and '}'"

从正确的角度来看,此处的下一个替换操作示例是将所有 'n' 字符替换为 '7' 个字符.在这种情况下,字符串的第一行{con}descens{ion}"应该变成{con}desce{7}s{ion}"而不是{co{7}}desce{7}s{io{7}}";根据这些标准,其他词将保持不变.

To put it into perspective, an example next replacement operation here would be to to replace all 'n' characters with '7' characters. In this case, the first line of the string, "{con}descens{ion}", should become "{con}desce{7}s{ion}" and not "{co{7}}desce{7}s{io{7}}"; the other words would remain the same based on these criteria.

有什么建议吗?

推荐答案

假设你的花括号总是平衡的,你可以在这里使用 Negative Lookahead.

Assuming your curly braces will always be balanced, you can use a Negative Lookahead here.

[a-zA-Z]+(?![^{]*\})

注意:这仅匹配 AZ 范围的字符,如果单词将包含空格或您有其他字符需要允许或不确定输入的类型,您可以在此处使用否定匹配.

Note: This only matches characters of the A to Z range, if words will include whitespace or you have other characters that need to be allowed or unsure of the type of input, you can use a negated match here.

[^}]+(?![^{]*\})

现场演示

这篇关于使用正则表达式查找不在两个字符之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆