• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

split and regexps

 
jeroen dijkmeijer
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello to all,

I have some code which has some perl like behavior and allows me to split a line with some separators onto a head and tail specifying an index. A negative index will start from the end of the string and will make the tail the head, handy if you're not sure on the number of columns in your list.


All works beautiful and as expected however, the split uses regexes to match the column separators, works for ~ but not for "|", which is treated as a regex special character, I may be able to pass in "\\|" but that upsets the join feature.
So my question is: is there a way to use split only on normal "string tokens" or are there other clever ways to get divide a string in the documented way.

Thanks in advance.
jeroen.
My question is there a way to make the split none regex like
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Or, if you're running JDK 5 or later,
 
jeroen dijkmeijer
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aah the quote functionality was something I was looking for!
good thing they put it in 5, too bad I'm bound to 1.4, I'll stick to the replace all functionality. Thanks for the lesson!
Jeroen.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In JDK 1.4, you can also use

String regex = "\\Q" + separator + "\\E";

That's actually what the later Pattern.quote() uses (unless the regex itself contains \\E internally).
 
Henry Wong
author
Marshal
Pie
Posts: 21496
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a JDK 1.4 version of a quote() method -- that functionally does the same thing as the JDK 1.5 version of the Pattern.quote() method.



Henry
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The \Q...\E thing is a carryover from Perl; there's no good reason to use it in Java, considering how much more complicated it is to work with. I've never understood why they used it in the quote() method, but at least we don't have to deal with it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic