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
113k96 gold badges307 silver badges430 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.5k2 gold badges32 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
72.9k12 gold badges98 silver badges155 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,5361 gold badge30 silver badges43 bronze badges
answered Sep 4, 2009 at 13:24
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,2644 gold badges29 silver badges40 bronze badges
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
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,01826 silver badges22 bronze badges
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: 13086


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:

Вопрос:
Картинка:
Ошибка:
C:UsersEamonprogrammingjava>javac shop/Main.java
.shopCatalogue.java:41: error: illegal escape character
Pattern.compile("^[A-Za-z][d]{4}$");
^
1 error
C:UsersEamonprogrammingjava>javac shop/Main.java
.shopCatalogue.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, которое будет правильно интерпретировано как десятичная ссылка.

Форум программистов Vingrad
| Модераторы: LSD, AntonSaburov |
Поиск: |
![]() ![]()
|
|
Опции темы |
| gogzor |
|
||
Шустрый Профиль Репутация: нет
|
Привет всем!
Компилятор выдаёт ошибку — illegal escape character , В чём проблема я не понял , помогите плиз. З.Ы Подкиньте плиз ссылок на хорошие факи по работе с регэкспами в яве. (желательно на русском) Заранее спасибо. |
||
|
|||
| VectorMan |
|
||
|
Antihero Профиль Репутация: 1
|
Может просто попробуешь удвоить бэкслеши?
Это сообщение отредактировал(а) VectorMan — 4.1.2007, 16:57 |
||
|
|||
| nerezus |
|
||
Вселенский отказник Профиль Репутация: нет
|
Фридл Дж. Регулярные выражения (2-е изд.), Питер 2003, 464 с., ISBN 5-272-00331-4 Добавлено @ 19:16 ——————— Сообщество художников Artsociety.ru |
||
|
|||
| gogzor |
|
||
Шустрый Профиль Репутация: нет
|
Регэксп вобще реальный |
||
|
|||
| batigoal |
|
||
Нелетучий Мыш Профиль
Репутация: 24
|
gogzor, вот тут еще есть официальный туториал: http://java.sun.com/docs/books/tutorial/es…egex/index.html ——————— «Чтобы правильно задать вопрос, нужно знать большую часть ответа» (Р. Шекли) |
||
|
|||
| Maksym |
|
||
. Профиль
Репутация: 14
|
Еще пару линков в тему: Using Regular Expressions in Java, java.util.regex Using Examples |
||
|
|||



















![]() ![]()
|
| Правила форума «Java» | |
|
|
Если Вам помогли, и атмосфера форума Вам понравилась, то заходите |
| 0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) |
| 0 Пользователей: |
| « Предыдущая тема | Java: Общие вопросы | Следующая тема » |
This simple regex program
import java.util.regex.*;
class Regex {
public static void main(String [] args) {
System.out.println(args[0]); // #1
Pattern p = Pattern.compile(args[0]); // #2
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()) {
System.out.println(m.start()+" "+m.group());
}
}
}
invoked by java regex "d" "sfdd1" compiles and runs fine.
But if #1 is replaced by Pattern p = Pattern.compile("d");, it gives compiler error saying illegal escape character. In #1 I also tried printing the pattern specified in the command line arguments. It prints d, which means it is just getting replaced by d in #2.
So then why won’t it throw any exception? At the end it’s string argument that Pattern.compile() is taking, doesn’t it detect illegal escape character then? Can someone please explain why is this behaviour?
asked Sep 24, 2012 at 21:33
![]()
3
A backslash character in a string literal needs to be escaped (preceded by a backslash). When passed in from the command line the string is not a string literal. The compiler complains because "d" is not a valid escape sequence (see Escape Sequences for Character and String Literals ).
answered Sep 24, 2012 at 21:36
hmjdhmjd
119k19 gold badges205 silver badges249 bronze badges
4
The character is used as an escape character for both Java string literals and regular expressions. This confuses many programmers. When you want to create a String in Java to represent a regular expression that has an escape character then you need to escape the Java escape character.
When passing the string in on the command line the JVM handles this for you and simply creates the String.
What you want is this
Pattern p = Pattern.compile("\d");
answered Sep 24, 2012 at 21:44
km1km1
2,3431 gold badge20 silver badges27 bronze badges
2
The backslash in Java results in an escape in strings. For example, the string "t" results in a tab character in java. This is also why "n" produces a newline.
In regular expressions, d is an escape with respect to the regular expression, not Java. This means in order to get d in a string literal, you have to type "\d" in the string. Basically, you have to escape the to get the literal value d, and then when Pattern compiles the regex, it further escapes the d to be parsed as a digit.
This can be confusing, but long story short, you should never have a single in a string literal for a regular expression since even the string literal "\n" gets parsed properly.
answered Sep 24, 2012 at 21:47
BrianBrian
16.9k6 gold badges41 silver badges65 bronze badges
I’m not entirely sure if I understand the question, but it seems like your problem is that you’re treating «d» as a Java escape character, which doesn’t exist. To treat it as a regex escape character, use «d» to escape the Java escape.
answered Sep 24, 2012 at 21:36
ChrisChris
4403 silver badges8 bronze badges
This simple regex program
import java.util.regex.*;
class Regex {
public static void main(String [] args) {
System.out.println(args[0]); // #1
Pattern p = Pattern.compile(args[0]); // #2
Matcher m = p.matcher(args[1]);
boolean b = false;
while(b = m.find()) {
System.out.println(m.start()+" "+m.group());
}
}
}
invoked by java regex "d" "sfdd1" compiles and runs fine.
But if #1 is replaced by Pattern p = Pattern.compile("d");, it gives compiler error saying illegal escape character. In #1 I also tried printing the pattern specified in the command line arguments. It prints d, which means it is just getting replaced by d in #2.
So then why won’t it throw any exception? At the end it’s string argument that Pattern.compile() is taking, doesn’t it detect illegal escape character then? Can someone please explain why is this behaviour?
asked Sep 24, 2012 at 21:33
![]()
3
A backslash character in a string literal needs to be escaped (preceded by a backslash). When passed in from the command line the string is not a string literal. The compiler complains because "d" is not a valid escape sequence (see Escape Sequences for Character and String Literals ).
answered Sep 24, 2012 at 21:36
hmjdhmjd
119k19 gold badges205 silver badges249 bronze badges
4
The character is used as an escape character for both Java string literals and regular expressions. This confuses many programmers. When you want to create a String in Java to represent a regular expression that has an escape character then you need to escape the Java escape character.
When passing the string in on the command line the JVM handles this for you and simply creates the String.
What you want is this
Pattern p = Pattern.compile("\d");
answered Sep 24, 2012 at 21:44
km1km1
2,3431 gold badge20 silver badges27 bronze badges
2
The backslash in Java results in an escape in strings. For example, the string "t" results in a tab character in java. This is also why "n" produces a newline.
In regular expressions, d is an escape with respect to the regular expression, not Java. This means in order to get d in a string literal, you have to type "\d" in the string. Basically, you have to escape the to get the literal value d, and then when Pattern compiles the regex, it further escapes the d to be parsed as a digit.
This can be confusing, but long story short, you should never have a single in a string literal for a regular expression since even the string literal "\n" gets parsed properly.
answered Sep 24, 2012 at 21:47
BrianBrian
16.9k6 gold badges41 silver badges65 bronze badges
I’m not entirely sure if I understand the question, but it seems like your problem is that you’re treating «d» as a Java escape character, which doesn’t exist. To treat it as a regex escape character, use «d» to escape the Java escape.
answered Sep 24, 2012 at 21:36
ChrisChris
4403 silver badges8 bronze badges
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}"
));
6 Answers
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
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 🙂
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}
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}
all you need to do is to put
*
ex: string ex = 'this is the character: *\s';
before your invalid character and not 8 !!!!!
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.
Почему я не могу использовать u000D и u000A как CR и LF в Java? При компиляции кода выдает ошибку:
String x = "u000A hello";//Error - Illegal escape character in string literal.
2 ответы
Экраны Unicode предварительно обрабатываются перед запуском компилятора. Следовательно, если поставить u000A в строковом литерале вроде этого:
String someString = "foou000Abar";
Он будет скомпилирован точно так, как если бы вы написали:
String someString = "foo
bar";
Придерживаться r (возврат каретки; 0x0D) и расширение n (перевод строки; 0x0A)
Бонус: Вы всегда можете получить от этого удовольствие, особенно с учетом ограничений большинства выделителей синтаксиса. В следующий раз, когда у вас будет секунда, попробуйте запустить этот код:
public class FalseIsTrue {
public static void main(String[] args) {
if ( false == true ) { //these characters are magic: u000au007du007b
System.out.println("false is true!");
}
}
}
ответ дан 05 окт ’10, 18:10
Потому что он попадает в диапазон Управляющие символы Unicode
Который U+0000–U+001F и U+007F.
Управляющие символы Unicode используются для управления интерпретацией или отображением текста, но сами эти символы не имеют визуального или пространственного представления.
Их можно избежать, используя как описано в ответе @Mark выше
ИЗ RFC:
2.5. Струны
Представление строк аналогично соглашениям, используемым в семействе языков программирования C. Строка начинается и заканчивается кавычками. Все символы Unicode могут быть помещены в кавычки, за исключением символов, которые необходимо экранировать: кавычки, обратная косая черта и управляющие персонажи
(От U + 0000 до U + 001F).Любой персонаж май сбежать.
ответ дан 20 апр.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
java
unicode
or задайте свой вопрос.








