Java illegal escape character ошибка

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

114k96 gold badges308 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

butterchicken's user avatar

butterchickenbutterchicken

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

Alan Moore

73.6k12 gold badges100 silver badges156 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,4661 gold badge30 silver badges45 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,3025 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,01827 silver badges22 bronze badges

1

I have done my .java file that changes registry data. But I am getting «illegal escape character» error on the line where Runtime.getRuntime().exec exists. Where is my mistake ?

import java.util.*;
import java.applet.Applet; 
import java.awt.*; 

class test {
  public static void main(String args[]) {
      try {
          Runtime.getRuntime().exec("REG ADD 'HKCUSoftwareMicrosoftInternet ExplorerMain' /V 'Start Page' /D 'http://www.stackoverflow.com/' /F");
      } catch (Exception e) {
          System.out.println("Error ocured!");
      }
  }
}

pb2q's user avatar

pb2q

58.3k19 gold badges146 silver badges147 bronze badges

asked Oct 15, 2012 at 4:23

user198989's user avatar

You need to escape the backslashes used in your path.

String windowsPath = "\Users\FunkyGuy\My Documents\Hello.txt";

answered Oct 15, 2012 at 4:25

jahroy's user avatar

jahroyjahroy

22.2k9 gold badges58 silver badges108 bronze badges

You need to escape with another , so replace with \ in your input string.

answered Oct 15, 2012 at 4:25

Bhesh Gurung's user avatar

Bhesh GurungBhesh Gurung

50.3k22 gold badges93 silver badges141 bronze badges

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. if you want to use it literally in a string, then you’ll need to escape it, by using a double-backslash.

answered Oct 15, 2012 at 4:25

pb2q's user avatar

pb2qpb2q

58.3k19 gold badges146 silver badges147 bronze badges

Back slashes in Java are special «escape» characters, they provide the ability to include things like tabs t and/or new lines n and lots of other fun stuff.

Needless to say, you to to «escape» them as well by adding an addition character…

'HKCU\Software\Microsoft\Internet Explorer\Main'

On a side note. I would use ProcessBuilder or at the very least, the version of Runtime#exec that uses array arguments.

It will save a lot of hassle when it comes to dealing with spaces within command parameters, IMHO

answered Oct 15, 2012 at 4:29

MadProgrammer's user avatar

MadProgrammerMadProgrammer

342k22 gold badges227 silver badges363 bronze badges

7

you need replace escape with \

below code will work

Runtime.getRuntime().exec("REG ADD 'HKCU\Software\Microsoft\Internet Explorer\Main' /V 'Start Page' /D 'http://www.stackoverflow.com/' /F");

answered Oct 15, 2012 at 4:29

subodh's user avatar

subodhsubodh

6,13612 gold badges51 silver badges73 bronze badges

Вопрос:

Картинка:

Ошибка:

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, которое будет правильно интерпретировано как десятичная ссылка.

Подскажите, пожалуйста
при такой записи получается ошибка 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

  • 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:

Понравилась статья? Поделить с друзьями:
  • Java heap space ошибка как исправить dbeaver
  • Java heap space ошибка декларации
  • Java heap space minecraft ошибка
  • Java float ошибка
  • Java else without if ошибка