1

I want to be able to escape symbols in path string so I could pass it to bash without quotes.

I.e. i have a file sample (1).txt.

I want to transform this string into sample\ \(1\).txt. Spaces and braces are an example of symbols, which should be definitely escaped.

I would like to use a method which will escape ALL characters which should be escaped.

Maybe there is one in default library or in some other popular library.

Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
Kirill
  • 6,762
  • 4
  • 51
  • 81
  • Possible duplicate of [How to split a string in Java](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Chris Gong Aug 19 '16 at 16:07
  • 3
    And what's wrong with passing them quoted? This seems to be an [XY problem](http://meta.stackexchange.com/q/66377/286538). Can you explain the actual issue you are facing? – RealSkeptic Aug 19 '16 at 16:09
  • The problem is it is only part of path, the other part is not controlled by me unfortunately – Kirill Aug 19 '16 at 16:12
  • 2
    I agree with RealSkeptic; this sounds like an XY problem. It sounds like you may be misusing bash (that is, using `bash -c 'command arg1 arg2'` instead of just `command` `arg1` `arg2`); normally, you pass arguments directly to ProcessBuilder, in which case you don’t need to quote them at all. – VGR Aug 19 '16 at 19:40
  • Welcome to Stack Overflow! Can you please have a better title and more detailed information in the content with your effort to solve the problem? – Enamul Hassan Aug 21 '16 at 22:20

3 Answers3

0

You can use String.replace() method for including or removing any characters before special characters.

Shahid
  • 2,288
  • 1
  • 14
  • 24
0

Look into the Pattern/Matcher/StringBuffer classes:

Pattern p = Pattern.compile("([ ()])"); //regex setup
Matcher m = p.matcher("replace these spaces (2).txt"); //sample input
StringBuffer s = new StringBuffer();
while (m.find())
    m.appendReplacement(s, "\\\\" + m.group(1));
m.appendTail(s); //add the last tail of code
System.out.println(s.toString());

Example output on running in main:

// replace\ these\ spaces\ \(2\).txt
tluh
  • 668
  • 1
  • 5
  • 16
0

You don't say what the criteria for choosing which characters are symbols, but assuming you want something that can be turned into a URI, then the java classes java.io.File and interface java.io.Path are provided for this reason (as well as a few other reasons).

Here's the java 7+ version:

// toASCIIString is not usually necessary
String withoutSymbols = new java.io.File("sample (1).txt").toUri().toASCIIString();
Paul Hicks
  • 13,289
  • 5
  • 51
  • 78