Example usage for java.lang String replaceFirst

List of usage examples for java.lang String replaceFirst

Introduction

In this page you can find the example usage for java.lang String replaceFirst.

Prototype

public String replaceFirst(String regex, String replacement) 

Source Link

Document

Replaces the first substring of this string that matches the given regular expression with the given replacement.

Usage

From source file:edu.umass.cs.utils.Util.java

public static InetAddress getInetAddressFromString(String s) throws UnknownHostException {
    return InetAddress.getByName(s.replaceFirst(".*/", ""));
}

From source file:edu.isi.wings.portal.classes.StorageHandler.java

public static String unzipFile(File f, String todirname, String toDirectory) {
    File todir = new File(toDirectory);
    if (!todir.exists())
        todir.mkdirs();//  ww w .j  a  v a 2s  .c o  m

    try {
        // Check if the zip file contains only one directory
        ZipFile zfile = new ZipFile(f);
        String topDir = null;
        boolean isOneDir = true;
        for (Enumeration<? extends ZipEntry> e = zfile.entries(); e.hasMoreElements();) {
            ZipEntry ze = e.nextElement();
            String name = ze.getName().replaceAll("/.+$", "");
            name = name.replaceAll("/$", "");
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (name.equals("__MACOSX"))
                continue;

            if (topDir == null)
                topDir = name;
            else if (!topDir.equals(name)) {
                isOneDir = false;
                break;
            }
        }
        zfile.close();

        // Delete existing directory (if any)
        FileUtils.deleteDirectory(new File(toDirectory + File.separator + todirname));

        // Unzip file(s) into toDirectory/todirname
        ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName();
            // OSX Zips carry an extra __MACOSX directory. Ignore it
            if (fileName.startsWith("__MACOSX")) {
                ze = zis.getNextEntry();
                continue;
            }

            // Get relative file path translated to 'todirname'
            if (isOneDir)
                fileName = fileName.replaceFirst(topDir, todirname);
            else
                fileName = todirname + File.separator + fileName;

            // Create directories
            File newFile = new File(toDirectory + File.separator + fileName);
            if (ze.isDirectory())
                newFile.mkdirs();
            else
                newFile.getParentFile().mkdirs();

            try {
                // Copy file
                FileOutputStream fos = new FileOutputStream(newFile);
                IOUtils.copy(zis, fos);
                fos.close();

                String mime = new Tika().detect(newFile);
                if (mime.equals("application/x-sh") || mime.startsWith("text/"))
                    FileUtils.writeLines(newFile, FileUtils.readLines(newFile));

                // Set all files as executable for now
                newFile.setExecutable(true);
            } catch (FileNotFoundException fe) {
                // Silently ignore
                //fe.printStackTrace();
            }
            ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();

        return toDirectory + File.separator + todirname;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.sourceforge.atunes.utils.StringUtils.java

/**
 * <p>//  w ww. j  a v a2  s . c o m
 * Returns a List containing strings of the array. Text between " chars, are
 * returned on a string
 * </p>
 * <p>
 * Example: {"This", "is\"", "a ", "test\""} will return: "This" "is" "a
 * test"
 * </p>
 * 
 * @param str
 *            String array
 * 
 * @return List containing strings of the array
 */
public static List<String> fromStringArrayToList(final String... str) {
    List<String> result = new ArrayList<String>();
    boolean openedQuotes = false;
    String auxStr = "";
    for (String s : str) {
        if (s.startsWith("\"") && s.endsWith("\"")) {
            result.add(s.replaceAll("\"", ""));
        } else if (s.endsWith("\"")) {
            openedQuotes = false;
            auxStr = StringUtils.getString(auxStr, " ", s.replaceAll("\"", ""));
            result.add(auxStr);
        } else if (s.startsWith("\"")) {
            openedQuotes = true;
            auxStr = s.replaceFirst("\"", "");
        } else if (openedQuotes) {
            auxStr = StringUtils.getString(auxStr, " ", s);
        } else {
            result.add(s);
        }
    }
    return result;
}

From source file:canreg.client.analysis.Tools.java

public static LinkedList<String> callR(String rScript, String rpath, String reportFileName)
        throws TableErrorException {
    LinkedList<String> filesCreated = new LinkedList<String>();
    Runtime rt = Runtime.getRuntime();
    ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(rpath);//from  www . ja  v a 2  s .c om
    commandList.add("CMD");
    commandList.add("BATCH");
    commandList.add("--vanilla");
    commandList.add("--slave");
    commandList.add(rScript);
    commandList.add(reportFileName);

    //String command = canreg.common.Tools.encapsulateIfNeeded(rpath)
    //        + " CMD BATCH --vanilla --slave "
    //        + canreg.common.Tools.encapsulateIfNeeded(rScript) + " "
    //        + canreg.common.Tools.encapsulateIfNeeded(reportFileName);
    System.out.println(commandList);
    Process pr = null;
    try {
        pr = rt.exec(commandList.toArray(new String[] {}));
        // collect the output from the R program in a stream
        // BufferedInputStream is = new BufferedInputStream(pr.getInputStream());
        pr.waitFor();
        BufferedInputStream is = new BufferedInputStream(new FileInputStream(reportFileName));
        // convert the output to a string
        String theString = convertStreamToString(is);
        Logger.getLogger(RTableBuilderGrouped.class.getName()).log(Level.INFO, "Messages from R: \n{0}",
                theString);
        // System.out.println(theString);
        // and add all to the list of files to return
        for (String fileName : theString.split("\n")) {
            if (fileName.startsWith("-outFile:")) {
                fileName = fileName.replaceFirst("-outFile:", "");
                if (new File(fileName).exists()) {
                    filesCreated.add(fileName);
                }
            }
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
    } catch (java.util.NoSuchElementException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
        if (pr != null) {
            BufferedInputStream errorStream = new BufferedInputStream(pr.getErrorStream());
            String errorMessage = convertStreamToString(errorStream);
            System.out.println(errorMessage);
            throw new TableErrorException("R says:\n \"" + errorMessage + "\"");
        }
    } catch (IOException ex) {
        Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (pr != null) {
            System.out.println(pr.exitValue());
        }
    }
    return filesCreated;
}

From source file:com.jigsforjava.string.StringUtils.java

/**
 * Converts the string (presumably a single word) from singular into plural
 * form./*w ww  . ja v a  2  s  .  c  o m*/
 * 
 * @param word a single word in singular form.
 * @return the plural form of the word.
 */
public static String pluralize(String word) {
    if (isNullOrEmpty(word))
        return word;

    for (Entry<String, String> rule : PLURALIZATION_RULES.entrySet()) {
        final String pattern = rule.getKey().toString();
        final String replacement = rule.getValue().toString();

        if (word.matches(pattern)) {
            return word.replaceFirst(pattern, replacement);
        }
    }

    return word.replaceFirst("([\\w]+)([^s])$", "$1$2s");
}

From source file:com.jigsforjava.string.StringUtils.java

/**
 * Converts the string (presumably a single word) from plural into singular
 * form.//from w ww.  ja  v  a  2  s .co m
 * 
 * @param word a single word in plural form.
 * @return the singular form of the word.
 */
public static String singularize(String word) {
    if (isNullOrEmpty(word))
        return word;

    for (Entry<String, String> rule : SINGULARIZATION_RULES.entrySet()) {
        final String pattern = rule.getKey().toString();
        final String replacement = rule.getValue().toString();

        if (word.matches(pattern)) {
            return word.replaceFirst(pattern, replacement);
        }
    }

    return word.replaceFirst("([\\w]+)s$", "$1");
}

From source file:Main.java

private static void transformInternal(final URIResolver xslResolver, final StreamSource xml,
        final InputSource xsl, final Map<String, Object> parameters, final StreamResult result)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerException {/*from   w w w  .j  a  va  2 s.c  o m*/
    final TransformerFactory tfactory = TransformerFactory.newInstance();
    tfactory.setURIResolver(xslResolver);

    // Does this factory support SAX features?
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // if so, we can safely cast
        final SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory);

        // create a Templates ContentHandler to handle parsing of the
        // stylesheet
        final javax.xml.transform.sax.TemplatesHandler templatesHandler = stfactory.newTemplatesHandler();
        templatesHandler.setDocumentLocator(emptyDocumentLocator);

        final XMLFilter filter = new XMLFilterImpl();
        filter.setParent(makeXMLReader());
        filter.setContentHandler(templatesHandler);

        // parse the stylesheet
        templatesHandler.setSystemId(xsl.getSystemId());
        filter.parse(xsl);

        // set xslt parameters
        final Transformer autobot = templatesHandler.getTemplates().newTransformer();
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                final String name = keys.next();
                final Object value = parameters.get(name);
                autobot.setParameter(name, value);
            }
        }

        // set saxon parameters
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                String name = keys.next();
                if (name.startsWith("saxon-")) {
                    final String value = parameters.get(name).toString();
                    name = name.replaceFirst("saxon\\-", "");
                    autobot.setOutputProperty(name, value);
                }
            }
        }

        // do the transform
        // logger.debug("SAX resolving systemIDs relative to: " +
        // templatesHandler.getSystemId());
        autobot.transform(xml, result);

    } else {
        throw new IllegalStateException("Factory doesn't implement SAXTransformerFactory");
    }
}

From source file:co.cask.cdap.data.tools.ReplicationStatusTool.java

private static String normalizedFileName(String fileName) {
    //while matching the filenames, ignore the IP addresses of the clusters
    String normalizedName;/*from   w  ww.j a v  a 2  s .c o m*/
    String ipv4Pattern = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
    String ipv6Pattern = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";
    normalizedName = fileName.replaceFirst(ipv4Pattern, "<hostname>");
    normalizedName = normalizedName.replaceFirst(ipv6Pattern, "<hostname>");
    return normalizedName;
}

From source file:com.basistech.lucene.tools.LuceneQueryTool.java

private static void validateOptions(Options options, String[] args)
        throws org.apache.commons.cli.ParseException {
    Set<String> optionNames = Sets.newHashSet();

    // non-generic forced by commons.cli api
    for (Object o : options.getOptions()) {
        Option option = (Option) o;
        optionNames.add(option.getLongOpt());
        String shortOpt = option.getOpt();
        if (shortOpt != null) {
            optionNames.add(shortOpt);//from   ww w  .ja  va 2  s  . c o m
        }
    }
    for (String arg : args) {
        if (arg.startsWith("-")) {
            String argName = arg.replaceFirst("-+", "");
            if (!optionNames.contains(argName)) {
                throw new org.apache.commons.cli.ParseException("Unrecognized option: " + arg);
            }
        }
    }
}

From source file:data.services.BaseParamService.java

public static Double uidFilter(Object uid) throws Exception {
    Double fuid;//  w ww.java 2s. c  o m
    String suid = StringAdapter.getString(uid);
    try {
        try {
            fuid = Double.valueOf(suid);
        } catch (NumberFormatException exc1) {
            suid = suid.replaceFirst("[,]", ".");
            suid = suid.replaceAll("[^0-9-.]*", "");
            fuid = Double.valueOf(suid);
        }
    } catch (NumberFormatException exc) {
        throw new Exception("    ?.");
    }
    return fuid;
}