f@0: /*
f@0: CCmI Editor - A Collaborative Cross-Modal Diagram Editing Tool
f@0:
f@0: Copyright (C) 2011 Queen Mary University of London (http://ccmi.eecs.qmul.ac.uk/)
f@0:
f@0: This program is free software: you can redistribute it and/or modify
f@0: it under the terms of the GNU General Public License as published by
f@0: the Free Software Foundation, either version 3 of the License, or
f@0: (at your option) any later version.
f@0:
f@0: This program is distributed in the hope that it will be useful,
f@0: but WITHOUT ANY WARRANTY; without even the implied warranty of
f@0: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
f@0: GNU General Public License for more details.
f@0:
f@0: You should have received a copy of the GNU General Public License
f@0: along with this program. If not, see .
f@0: */
f@0:
f@0: package uk.ac.qmul.eecs.ccmi.utils;
f@0:
f@0: /**
f@0: * A utility class providing static methods to escape one or more characters.
f@0: *
f@0: */
f@0: public class CharEscaper {
f@0: /**
f@0: * Replaces the new line character with a '|' in the {@code String} passed as argument.
f@0: * The original {@code String} can be restored by passing the returned {@code String} to
f@0: * {@link #restoreNewline(String)}. Existing '|' characters will be escaped in order not to miss
f@0: * them in the restore process.
f@0: * @param s the {@code String} to remove new line characters from
f@0: * @return a {@code String} where all new line characters have been replaced by '|'
f@0: */
f@0: public static String replaceNewline(String s){
f@0: String result = s.replace("|", "'|");
f@0: return result.replace('\n', '|');
f@0: }
f@0:
f@0: /**
f@0: * Restores a {@code String} whose new line characters have been previously replaced by
f@0: * {@link #replaceNewline(String)}, to the original form.
f@0: * @param s the string to be restored
f@0: * @return the restored string
f@0: */
f@0: public static String restoreNewline(String s){
f@0: String result = s.replaceAll("([^'])\\|","$1\n");
f@0: return result.replace("'|", "|");
f@0: }
f@0:
f@0: /**
f@0: * Escapes a set of character with another character.
f@0: * @param s The {@code String} whose characters must be escaped.
f@0: * @param charsToEscape The set of characters to escape
f@0: * @param escapeChar The escape character
f@0: * @return a new {@code String} where characters in {@code charsToEscape} have been escaped
f@0: * by {@code escapeChar}.
f@0: */
f@0: public static String escapeCharSequence(String s, CharSequence charsToEscape, char escapeChar ){
f@0: String result = s;
f@0: for(int i=0;i< charsToEscape.length();i++){
f@0: char c = charsToEscape.charAt(i);
f@0: if(c == escapeChar)
f@0: throw new IllegalArgumentException("escape character cannot be in chars to escape sequence");
f@0: for(int j=0;j