[英]Skip regex matching between certain characters
In the following program I'm trying to prefix any text starting with "_" with the word "app": 在下面的程序中,我试图将以“_”开头的任何文本加上“app”一词的前缀:
String s = "C_NAME=\"usco _f2 re_col\" &&_f1=\"ot\" && _f1 = \"fd\"|stats count(_f1)|fields _f1, f3|filter match(app_f1,\"get\")|extract field=\".*?\\[\\d+\\s+(?<_LogLevel>\\w+).*";
StringBuilder s1 = new StringBuilder(s);
java.util.regex.Pattern p = java.util.regex.Pattern.compile(".*?((?<!\\w)_\\w+).*?",
Pattern.UNICODE_CHARACTER_CLASS);
Matcher m = p.matcher(s);
while (m.find()) {
String fieldname = m.group(1);
s1.replace(m.start(1), m.end(1), "app" + fieldname);
m.reset(s1);
}
System.out.println(s1.toString());
But, I've one more clause to take care: the above regex shouldn't append the text "app" to the text starting with "_" if the text is located in between a pair of double quotes. 但是,我还有一个要注意的条款:如果文本位于一对双引号之间,则上述正则表达式不应将文本“app”附加到以“_”开头的文本中。 In this particular example the text "_f2" shouldn't get prefixed.
在此特定示例中,文本“_f2”不应加前缀。 Any clues on how to achieve this functionality?
有关如何实现此功能的任何线索?
Update: 更新:
The following regex workd fine in my case: 以下正则表达式在我的案例中工作得很好:
Pattern p = Pattern.compile(".*?(?:\"[^\"]*\"|((?<!\\w)_\\w+)).*?",
Pattern.UNICODE_CHARACTER_CLASS);
Since (*SKIP)(*FAIL)
is not implemented in Java
, you'll need to come up with some logic on your own: 由于
(*SKIP)(*FAIL)
未在Java
实现,因此您需要自己提出一些逻辑:
What_I_want_to_avoid|(What_I_want_to_match)
So, in your case: 所以,在你的情况下:
"[^"]*"|(\b_\w+)
# left: anything between two double quotes
# right: a word boundary, an underscore and at least one word character
Match everything unwanted in the left branch and if group 1 exists, do a replacement here. 匹配左侧分支中不需要的所有内容,如果组1存在,请在此处进行替换。
See a demo on regex101.com . 请参阅regex101.com上的演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.