Here you can find the source of splitQuotedTokens(String str)
Parameter | Description |
---|---|
str | a parameter |
public static String[] splitQuotedTokens(String str)
//package com.java2s; /*//from w w w. j av a 2s.c om * Created on Jun 9, 2008 * Created by Paul Gardner * * Copyright (C) Azureus Software, Inc, All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ import java.util.ArrayList; import java.util.List; public class Main { /** * splits space separated tokens respecting quotes (either " or ' ) * @param str * @return */ public static String[] splitQuotedTokens(String str) { List<String> bits = new ArrayList<String>(); char quote = ' '; boolean escape = false; boolean bit_contains_quotes = false; String bit = ""; char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (Character.isWhitespace(c)) { c = ' '; } if (escape) { bit += c; escape = false; continue; } else if (c == '\\') { escape = true; continue; } if (c == '"' || c == '\'' && (i == 0 || chars[i - 1] != '\\')) { if (quote == ' ') { bit_contains_quotes = true; quote = c; } else if (quote == c) { quote = ' '; } else { bit += c; } } else { if (quote == ' ') { if (c == ' ') { if (bit.length() > 0 || bit_contains_quotes) { bit_contains_quotes = false; bits.add(bit); bit = ""; } } else { bit += c; } } else { bit += c; } } } if (quote != ' ') { bit += quote; } if (bit.length() > 0 || bit_contains_quotes) { bits.add(bit); } return (bits.toArray(new String[bits.size()])); } }