简体   繁体   English

无效的转义序列

[英]Invalid escape sequence

I would like to filter out all words containing 1 number and 3 capital letters with a total length of 4. See my example here: http://gskinner.com/RegExr/?32taa 我想过滤掉所有单词,这些单词包含1个数字和3个大写字母,总长度为4。在这里查看我的示例: http : //gskinner.com/RegExr/?32taa

ArrayList<String> result = new ArrayList<String>();


for(int i = 0; i <= 10; i++){

    String message = resp.data.get(i).message;

    Matcher m = MY_PATTERN.matcher("\b(?=[^\d]*\d[^\d]*)[A-Z\d]{4}\b");

        while (m.find()) {
            String s = m.group(1);
            result.add(s);
        }
}

But when i pass my regexp pattern to the matcher method, i get the error: 但是当我将正则表达式模式传递给matcher方法时,出现错误:

Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )

Do I need to swap \\d with another letter? 我是否需要将\\d换成另一个字母?

Regex don't go well with String ... Regex不适用于String ...

So u need to use \\\\d instead of \\d 因此,您需要使用\\\\d而不是\\d

- When you write \\ java expects either n or b or t or a and few others... after it, but when you give d it gets the shock of its life, and think what the hell.. i don't know nothing about \\d , So we need to tell java that \\ should be taken literally by it instead of expecting it as escape character. -当您编写\\ java时,它期望nbta以及其他几个符号…… 之后 ,但是当您给d它会给它带来生命的震撼,并想一想到底。.我什么都不知道关于\\d ,因此我们需要告诉java \\ 应该按字面意义取而代之,而不是期望它作为转义符。

- In the case of . -如果是 (dot) it becomes even more complicated, when you give "." (点)当您输入"."时,情况变得更加复杂"." java takes it literally but its a regex so you need to make it look like that so you prefix it with \\ , so it becomes \\. java从字面上理解它,但是它是一个正则表达式,因此您需要使其看起来像这样,因此在其前面加上\\ ,因此它变为\\. , now again the same problem as the earlier one begins as now java accepts n or b etc after \\ but it gets a "." ,现在又出现了与以前的问题相同的问题,因为现在Java在\\之后接受nb等,但它得到一个"." , so we again prefix it with another \\ , so now it becomes \\\\. ,因此我们再次为它加上另一个\\前缀,现在它变成\\\\.

In Java, you need to escape the backslash with an extra backslash, when representing the pattern in string. 在Java中,你需要躲避backslash加上额外的反斜杠,表示字符串的模式时。

So, \\b should be \\\\b , and \\d should be \\\\d . 因此, \\b应该是\\\\b ,而\\d应该是\\\\d

Your code has two issues: 您的代码有两个问题:

Use regex pattern 使用正则表达式模式

\\b(?=[A-Z]*\\d[A-Z]*\\b)[A-Z\\d]{4}\\b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM