Меню

Illegal escape character in string literal java ошибка

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}"
));

Community's user avatar

asked Sep 4, 2009 at 13:17

Thomas Owens's user avatar

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

butterchicken's user avatar

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's user avatar

Alan Moore

72.9k12 gold badges98 silver badges155 bronze badges

answered Sep 4, 2009 at 13:22

willcodejavaforfood's user avatar

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

asalamon74's user avatar

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's user avatar

Melquiades

8,5361 gold badge30 silver badges43 bronze badges

answered Sep 4, 2009 at 13:24

Christopher Klewes's user avatar

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

Daniel's user avatar

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

snaveware's user avatar

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

MystikSpiral's user avatar

MystikSpiralMystikSpiral

5,01826 silver badges22 bronze badges

1


posted 14 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

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


  • Likes 1
  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

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

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Miklos is indeed correct, shifting to the beginners forum, more people will gain benefit from this if they search there.


posted 14 years ago


  • Likes 1
  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

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

Chrome
Java
Linux


posted 14 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

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

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

And check letter case at the readLine method it should be:

wood burning stoves

Вопрос:

Картинка:

Ошибка:

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

Поиск:

Ответ в темуСоздание новой темы
Создание опроса
> Ошибка — illegal escape character. При работе с Regexp. 

:(

   

Опции темы

gogzor
Дата 4.1.2007, 16:54 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Шустрый
*

Профиль
Группа: Участник
Сообщений: 134
Регистрация: 21.9.2006

Репутация: нет
Всего: нет

Привет всем!
Есть простой код :

Код

public static void main(String[] args) throws MalformedURLException
    {
      try
      {
          try
          {
       URL url = new URL("http://www.myurl.com");
       BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
       String str;
        while ((str = in.readLine()) != null)
        {
         String patternStr = "d{1,5}d{1,5}d{1,5}d{1,5}:d{1,5}";
          Pattern pattern = Pattern.compile(patternStr);
          Matcher matcher = pattern.matcher(str);
          while (matcher.find())
          {
              String match = matcher.group();
          }

                  }
          } catch (PatternSyntaxException e){
          }
      } catch (IOException e) {   
      }
    }

Компилятор выдаёт ошибку — illegal escape character , 
ссылаясь на это — String patternStr = «d{1,5}d{1,5}d{1,5}d{1,5}:d{1,5}»;

В чём проблема я не понял , помогите плиз.

З.Ы Подкиньте плиз ссылок на хорошие факи по работе с регэкспами в яве. (желательно на русском)

Заранее спасибо.

PM MAIL   Вверх
VectorMan
Дата 4.1.2007, 16:56 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Antihero
*

Профиль
Группа: Участник
Сообщений: 110
Регистрация: 9.4.2006

Репутация: 1
Всего: 4

Может просто попробуешь удвоить бэкслеши?  smile

Код
"\d{1,5}\d{1,5}\d{1,5}\d{1,5}\:\d{1,5}"

Это сообщение отредактировал(а) VectorMan — 4.1.2007, 16:57

PM   Вверх
nerezus
Дата 4.1.2007, 19:14 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Вселенский отказник
****

Профиль
Группа: Участник
Сообщений: 3330
Регистрация: 15.6.2005

Репутация: нет
Всего: 43

Цитата
З.Ы Подкиньте плиз ссылок на хорошие факи по работе с регэкспами в яве. (желательно на русском)

Фридл Дж. Регулярные выражения (2-е изд.), Питер 2003, 464 с., ISBN 5-272-00331-4

Добавлено @ 19:16 
Кстати, у тя регексп чисто для примера? Ибо бредовый )

———————

Сообщество художников Artsociety.ru

PM MAIL WWW   Вверх
gogzor
Дата 5.1.2007, 00:06 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Шустрый
*

Профиль
Группа: Участник
Сообщений: 134
Регистрация: 21.9.2006

Репутация: нет
Всего: нет

Регэксп вобще реальный  smile 
Спасибо за название книги , уже скачал , почитаю.

PM MAIL   Вверх
batigoal
Дата 5.1.2007, 15:05 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Нелетучий Мыш
****

Профиль
Группа: Участник Клуба
Сообщений: 6423
Регистрация: 28.12.2004
Где: Санктъ-Петербургъ

Репутация: 24
Всего: 151

gogzor, вот тут еще есть официальный туториал: http://java.sun.com/docs/books/tutorial/es…egex/index.html

———————

«Чтобы правильно задать вопрос, нужно знать большую часть ответа» (Р. Шекли)
ЖоржЖЖ

PM WWW   Вверх
Maksym
Дата 6.1.2007, 15:21 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

.
***

Профиль
Группа: Участник Клуба
Сообщений: 1456
Регистрация: 19.8.2005
Где: Odessa, Black Sea

Репутация: 14
Всего: 62

Еще пару линков в тему: Using Regular Expressions in Java, java.util.regex Using Examples

PM MAIL   Вверх



















Ответ в темуСоздание новой темы
Создание опроса
Правила форума «Java»
LSD
 
AntonSaburov

powerOn
 
tux

javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки
    кода. Используйтe чекбокс «транслит«, если у Вас
    нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка «Пометить как решённый» находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите
к нам чаще! С уважением,
LSD,
AntonSaburov,
powerOn,
tux, javastic.

 

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

Shades88's user avatar

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

hmjd's user avatar

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

km1's user avatar

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

Brian's user avatar

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

Chris's user avatar

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

Shades88's user avatar

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

hmjd's user avatar

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

km1's user avatar

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

Brian's user avatar

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

Chris's user avatar

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 задайте свой вопрос.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Illegal constructor вайлдберриз ошибка
  • Ilife v8s ошибка e41