I’m working on a solution to a previous question, as best as I can, using regular expressions. My pattern is
"\d{4}\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}"
According to NetBeans, I have two illegal escape characters. I’m guessing it has to do with the \d and \w, but those are both valid in Java. Perhaps my syntax for a Java regular expression is off…
The entire line of code that is involved is:
userTimestampField = new FormattedTextField(
new RegexFormatter(
"\d{4}\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}"
));
asked Sep 4, 2009 at 13:17
Thomas OwensThomas Owens
115k98 gold badges311 silver badges431 bronze badges
3
Assuming this regex is inside a Java String
literal, you need to escape the backslashes for your \d
and \w
tags:
"\\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}"
This gets more, well, bonkers frankly, when you want to match backslashes:
public static void main(String[] args) {
Pattern p = Pattern.compile("\\\\\\\\"); //ERM, YEP: 8 OF THEM
String s = "\\\\";
Matcher m = p.matcher(s);
System.out.println(s);
System.out.println(m.matches());
}
\\ //JUST TO MATCH TWO SLASHES :(
true
answered Sep 4, 2009 at 13:23
butterchickenbutterchicken
13.6k2 gold badges33 silver badges43 bronze badges
0
Did you try "\\d"
and "\\w"
?
-edit-
Lol I posted the right answer and get down voted and then I notice that stackoverflow escapes backslashes so my answer appeared wrong
Alan Moore
74k12 gold badges100 silver badges156 bronze badges
answered Sep 4, 2009 at 13:22
1
What about the following: \\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}
answered Sep 4, 2009 at 13:23
2
Have you tried this?
\\d{4}\\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}
Melquiades
8,4961 gold badge31 silver badges46 bronze badges
answered Sep 4, 2009 at 13:24
I had a similar because I was trying to escape characters such as -,*$ which are special characters in regular expressions but not in java.
Basically, I was developing a regular expression https://regex101.com/ and copy pasting it to java.
I finally realized that because java takes regex as string literals, the only characters that should be escaped are the special characters in java ie. \ and «
So in this case \\d should work.
However, anyone having a similar problem like me in the future, only escaped double quotes and backslashes.
answered Sep 14, 2022 at 6:29
1
all you need to do is to put
*\
ex: string ex = 'this is the character: *\\s';
before your invalid character and not 8 \ !!!!!
answered Feb 12, 2015 at 1:12
DanielDaniel
3,3205 gold badges30 silver badges40 bronze badges
I think you need to add the two escaped shortcuts into character classes. Try this: "[\d]{4}[\w]{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}"
—Good Luck.
answered Sep 4, 2009 at 13:22
MystikSpiralMystikSpiral
5,01827 silver badges22 bronze badges
1
Вопрос:
Картинка:
Ошибка:
C:\Users\Eamon\programming\java>javac shop/Main.java
.\shop\Catalogue.java:41: error: illegal escape character
Pattern.compile("^[A-Za-z][\d]{4}$");
^
1 error
C:\Users\Eamon\programming\java>javac shop/Main.java
.\shop\Catalogue.java:41: error: illegal escape character
Pattern.compile("^[A-Za-z][\p{Digit}]{4}$");
^
1 error
Код:
Pattern.compile("^[A-Za-z][\p{Digit}]{4}$");
Ссылка:
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#sum
Лучший ответ:
вам нужно убежать \d
и \p
с дополнительной обратной косой чертой, поскольку они не являются допустимыми escape-последовательностями.
"^[A-Za-z][\d]{4}$"
должно быть
"^[A-Za-z][\\d]{4}$"
а также
"^[A-Za-z][\p{Digit}]{4}$"
должно быть
"^[A-Za-z][\\p{Digit}]{4}$"
Ответ №1
Использовать escape-символ
Pattern.compile("^[A-Za-z][\\p{Digit}]{4}$");
Pattern.compile("^[A-Za-z][\\d]{4}$");
См. Пример примера LIVE DEMO
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
Pattern replace = Pattern.compile("^[A-Za-z][\\d]{4}$");
Matcher matcher1 = replace.matcher("A1234");
System.out.println("Output of A1234 = " + matcher1.replaceAll("ITS REPLACED"));
Matcher matcher2 = replace.matcher("F87652");
System.out.println("Output of F87652 = " + matcher2.replaceAll("ITS REPLACED"));
}
}
ВЫВОД:
Output of A1234 = ITS REPLACED
Output of F87652 = F87652
Ответ №2
В игре есть два уровня: вы пишете регулярное выражение внутри литерала строки Java в исходном файле. Прежде всего, часть Java String должна быть правильно экранирована, и здесь, где ошибка illegal escape character
возникает из: \d
недействительна в любом литерале Java String, даже если вы пишете регулярное выражение. Компилятор javac
– это тот, который собирается прочитать этот текст и преобразовать его во внутреннее значение String
, и в этом значении \\
будет неизолировано и на самом деле появится соответствующий \d
.
Во время выполнения, когда на самом деле создается регулярное выражение, оно увидит неизменяемое строковое значение, таким образом, \d
, которое будет правильно интерпретировано как десятичная ссылка.
Подскажите, пожалуйста
при такой записи получается ошибка Illegal escape character in string literal. хотя \ должен указывать на то, что ? это символ, а не квантификатор
(хочу отбросить первую часть строки, до символа ?)
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String url = reader.readLine();
reader.close();
String result = url.split("\?")[1];
прокатило только так, но это же неправильно? должны работать хотя бы круглые скобки
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String url = reader.readLine();
reader.close();
String result = url.split("[?]")[1];
posted 14 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
Dear Sir,
While complile this code the error message display that «Illegal escape character».Please guide me to rectify this code.
The data.txt file contains:->Sumanta,Sagar,Harish
Thanks and Regards
Sumanta Panda
[ November 21, 2008: Message edited by: Martijn Verburg ]
posted 14 years ago
-
1
-
Number of slices to send:
Optional ‘thank-you’ note:
Hi,
I think you should write
If you want to write a \ in a String literal you have to write \\, anyway Java compiler interprets it as an escape character. Since no such escape characters as \T or \d the java compiler reports an error.
Regards,
Miki
posted 14 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
Miklos is indeed correct, shifting to the beginners forum, more people will gain benefit from this if they search there.
posted 14 years ago
-
1
-
Number of slices to send:
Optional ‘thank-you’ note:
Another option is using forward slashes. File is smart enough to convert those to backslashes when accessing the actual file system.
lowercase baba
Posts: 13089
posted 14 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
Generally speaking, when the compiler gives you an error message, it tells you more than just «illegal escape character». It will show you the line and even the exact spot it thinks the error actually is:
It GREATLY helps people help you if you post the ENTIRE message. This lets a reader instantly focus in on where the problem is, rather than having to parse you entire java file and GUESS.
Just a little helpful tip for next time.
[ November 21, 2008: Message edited by: fred rosenberger ]
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
posted 11 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
And check letter case at the readLine method it should be:
What is the meaning of illegal escape character error in Java?
If you want to write a in a String literal you have to write \, anyway Java compiler interprets it as an escape character. Since no such escape characters as T or d the java compiler reports an error.
How do I change the escape character in Java?
“replace function in java removes escape characters” Code Answer
- String str= “This#string%contains^special*characters&.”;
- str = str. replaceAll(“[^a-zA-Z0-9]”, ” “);
- System. out. println(str);
What is illegal escape character?
5 Answers. The character ” is a special character and needs to be escaped when used as part of a String, e.g., “”.
How do you escape the escape character in Java?
Single quotes don’t need escaping because all Java strings are delimited by double quotes. Single quotes delimit character literals. So in a character literal, you need to escape single quotes, e.g. ”’ . So all you need is “\’” , escaping only the backslash.
You need to escape with another , so replace with \ in your input string. You need to escape the backslash characters in your registry path string: “REG ADD `HKCU\Software\ … The backslash character has a special meaning in strings: it’s used to introduce escape characters.
Why is an illegal character in Java?
The JavaScript exception “illegal character” occurs when there is an invalid or unexpected token that doesn’t belong at this position in the code.
How do you escape special characters?
Escape Characters
Use the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped. Note: If you use braces to escape an individual character within a word, the character is escaped, but the word is broken into three tokens.
How do I remove an escape character from a JSON string in Java?
On the receiving end, if you really want to, you could just do myJsonString = myJsonString. replaceAll(“\”,””); But do note that those escape characters in no way make the JSON invalid or otherwise semantically different — the ‘/’ character can be optionally escaped with ” in JSON.
What is an escape character in Java?
Escape sequences are used to signal an alternative interpretation of a series of characters. In Java, a character preceded by a backslash () is an escape sequence. The Java compiler takes an escape sequence as one single character that has a special meaning.
What does unclosed character literal mean in Java?
Unclosed Character Literal. Means, you started with ‘ single quote, so compiler just expects a single character after opening ‘ and then a closing ‘ . Hence, the character literal is considered unclosed and you see the error. So, either you use char data type and ‘ single quotes to enclose single character.
What is unclosed string literal in Java?
The “unclosed string literal” error message is created when the string literal ends without quotation marks and the message will appear on the same line as the error. … The string literal does not end with quote marks. This is easy to correct by closing the string literal with the needed quote mark.
What is escape character in HTML?
A character escape is a way of representing a character in source code using only ASCII characters. In HTML you can escape the euro sign € in the following ways. … A trailing space is treated as part of the escape, so use 2 spaces if you actually want to follow the escaped character with a space.
Is an escape sequence?
An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal, but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly.
How do you escape brackets in regex Java?
The first backslash escapes the second one into the string, so that what regex sees is ] . Since regex just sees one backslash, it uses it to escape the square bracket. In regex, that will match a single closing square bracket. If you’re trying to match a newline, for example though, you’d only use a single backslash.