"无效的转义序列(有效的是\ B \吨\ñ\ F \ r \" \'\\)"语法错误的是、序列、有效、语法错误

2023-09-06 17:34:56 作者:拼命微笑却扯痛了嘴角

我写了code匹配的文件路径具有extenstion .ncx,

 模式= Pattern.compile($(\\ | \ /)[A-ZA-Z0-9 _] / NCX。);
 匹配器匹配= pattern.mather(\ sample.ncx);
 

这显示了一个无效的转义序列(有效的是\ B \吨\ñ\ F \ r \\'\)语法错误的图案。我怎样才能解决这个问题。

解决方案

 模式P = Pattern.compile([/ \\\\]([A-ZA-Z0-9 _ ] + \\ NCX)$)。
匹配器米= p.matcher(\\ sample.ncx);
如果(m.find())
{
  System.out.printf(文件名是'%s'的%N,m.group(1));
}
 

输出:

 的文件名是'sample.ncx
 
Python程序开发 第十章 正则表达式 ヾ ω o那么复杂的正则表达式看完这一篇就懂啦

$ 锚的比赛到字符串的末尾(或在多行模式的行的结尾)。它属于在的结束你的正则表达式的的,而不是开始。

[/ \\\\] 是字符类匹配一个斜杠或反斜杠。反斜线必须是双转义,因为它具有特殊的意义无论是在正则表达式和一个字符串。正斜杠做的没有的要求逃脱。

[A-ZA-Z0-9 _] + 匹配一个或多个列出的字符;未经加号,你只匹配的一个的。

第二个斜杠在你的正则表达式是没有意义的,但你需要一个反斜杠有逃脱的点的当然是 - 并且,反斜线来转义为Java字符串。

由于我从交替切换( | )以字符类的斜线,已不再需要在你的正则表达式的括号内。相反,我用它们来捕捉中的实际文件名,只是为了演示如何这样做了。

I wrote code for matching filepath which have extenstion .ncx ,

 pattern = Pattern.compile("$(\\|\/)[a-zA-Z0-9_]/.ncx");
 Matcher matcher = pattern.mather("\sample.ncx");

This shows a invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ ) syntax error pattern. How can I fix it.

解决方案

Pattern p = Pattern.compile("[/\\\\]([a-zA-Z0-9_]+\\.ncx)$");
Matcher m = p.matcher("\\sample.ncx");
if (m.find())
{
  System.out.printf("The filename is '%s'%n", m.group(1));
}

output:

The filename is 'sample.ncx'

$ anchors the match to the end of the string (or to the end of a line in multiline mode). It belongs at the end of your regex, not the beginning.

[/\\\\] is a character class that matches a forward-slash or a backslash. The backslash has to be double-escaped because it has special meaning both in a regex and in a string literal. The forward-slash does not require escaping.

[a-zA-Z0-9_]+ matches one or more of the listed characters; without the plus sign, you were only matching one.

The second forward-slash in your regex makes no sense, but you do need a backslash there to escape the dot--and of course, the backslash has to be escaped for the Java string literal.

Because I switched from the alternation (|) to a character class for the leading slash, the parentheses in your regex were no longer needed. Instead, I used them to capture the actual filename, just to demonstrate how that's done.