This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Hands On Software Engineering with Python and have Brian Allbey on-line!
See this thread for details.
Win a copy of Hands On Software Engineering with Python this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

why compile error in "Pattern.compile()?  RSS feed

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, all
I want a pattern consists only a single backslash(\)
so I wrote Pattern.compile("\\");
but compiler complains like the following

why?
thx
--eliot
[ November 22, 2003: Message edited by: Eliot Skywalker ]
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're actually dealing with two compilers here - the javac compiler, and the pattern compiler. And both compilers use \ to signal an escape sequence, and \\ to signal a normal \. So the problem is:
You start with a String literal:
"\\"
The javac compiler sees this and interprets it to mean
\
The the pattern compiler looks at it, sees a single \, and is confused, because \ needs to have something after it, like \n or \\. So, it gives you an error message.
Instead, start with:
"\\\\"
javac will interpret this as
\\
and the pattern compiler will see this as
\
which is what you wanted. The rule of thumb is, for every plain literal \ you have in your intended pattern text, put four \'s in the String literal you compile to get the pattern. Yeah, it's weird, but it works.
 
Eliot Skywalker
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you,Jim
so I'll have to write
str.replaceAll("\\\\","\\\\\\\\")
something like that

I tested it,like you've said, weird,but it works
-eliot
 
The harder you work, the luckier you get. This tiny ad brings luck - just not good luck or bad luck.
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!