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:org.zilverline.extractors.AbstractExtractor.java

/**
 * Get a ISBN number from the given text.
 * // ww  w.  j a v a2 s  .  c  o  m
 * @param text the plain text, can be null
 * @return a valid ISBNnumber (10 characters without -) or else ""
 */
public static String getISBNFromContent(final String text) {
    if (text == null) {
        return "";
    }
    // ISBN:0764543857
    String ISBNnumber = "";
    int j;
    // does text contain ISBN or isbn?
    if (((j = text.indexOf("ISBN")) != -1) || (j = text.indexOf("isbn")) != -1) {
        // look 25 characters forward
        ISBNnumber = text.substring(j, j + 25);
        // remove ISBN.. (all text until first number)
        ISBNnumber = ISBNnumber.replaceFirst("[\\D]+", "");
        // remove all non-valid ISBN characters (0-9xX and - seem valid), remove - as well
        ISBNnumber = ISBNnumber.replaceAll("[^0-9xX]", "");
        if (ISBNnumber.length() > 10) {
            ISBNnumber = ISBNnumber.substring(0, 10);
        }
        log2.debug("possible ISBN found: " + ISBNnumber);
        if (!Utils.isValidISBNNumber(ISBNnumber)) {
            return "";
        }
    }
    return ISBNnumber;
}

From source file:com.keybox.manage.db.SessionAuditDB.java

/**
 * returns terminal logs for user session for host system
 *
 * @param sessionId     session id/*from  w w w . j  ava2 s.  c  om*/
 * @param instanceId    instance id for terminal session
 * @return session output for session
 */
public static List<SessionOutput> getTerminalLogsForSession(Connection con, Long sessionId,
        Integer instanceId) {

    List<SessionOutput> outputList = new LinkedList<>();
    try {
        PreparedStatement stmt = con.prepareStatement(
                "select * from terminal_log where instance_id=? and session_id=? order by log_tm asc");
        stmt.setLong(1, instanceId);
        stmt.setLong(2, sessionId);
        ResultSet rs = stmt.executeQuery();
        StringBuilder outputBuilder = new StringBuilder("");
        while (rs.next()) {
            outputBuilder.append(rs.getString("output"));
        }

        String output = outputBuilder.toString();
        output = output.replaceAll("\\u0007|\u001B\\[K|\\]0;|\\[\\d\\d;\\d\\dm|\\[\\dm", "");
        while (output.contains("\b")) {
            output = output.replaceFirst(".\b", "");
        }
        DBUtils.closeRs(rs);

        SessionOutput sessionOutput = new SessionOutput();
        sessionOutput.setSessionId(sessionId);
        sessionOutput.setInstanceId(instanceId);
        sessionOutput.getOutput().append(output);

        outputList.add(sessionOutput);

        DBUtils.closeRs(rs);

        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    return outputList;

}

From source file:io.spring.initializr.metadata.InitializrConfiguration.java

static String cleanPackageName(String packageName) {
    String[] elements = packageName.trim().replaceAll("-", "").split("\\W+");
    StringBuilder sb = new StringBuilder();
    for (String element : elements) {
        element = element.replaceFirst("^[0-9]+(?!$)", "");
        if (!element.matches("[0-9]+") && sb.length() > 0) {
            sb.append(".");
        }//from ww w  .j  av a2 s .c  o  m
        sb.append(element);
    }
    return sb.toString();
}

From source file:it.anyplace.sync.core.security.KeystoreHandler.java

public static byte[] deviceIdStringToHashData(String deviceId) {
    checkArgument(deviceId.matches(/* ww w.j a v  a2s .co  m*/
            "^[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}$"),
            "device id syntax error for deviceId = %s", deviceId);
    String base32data = deviceId.replaceFirst("(.{7})-(.{6}).-(.{7})-(.{6}).-(.{7})-(.{6}).-(.{7})-(.{6}).",
            "$1$2$3$4$5$6$7$8") + "===";
    byte[] binaryData = BaseEncoding.base32().decode(base32data);
    checkArgument(binaryData.length == Hashing.sha256().bits() / 8);
    return binaryData;
}

From source file:com.aw.core.dao.DAOSql.java

public static String buildSQL(String sql, Object[] sqlParams) {
    if (sqlParams == null)
        return sql;

    for (Object sqlParam : sqlParams) {
        if (sqlParam instanceof String)
            sqlParam = "'" + sqlParam + "'";
        sql = sql.replaceFirst("\\?", sqlParam == null ? "NULL" : sqlParam.toString());
    }/*from   www.j  av  a 2  s  . co  m*/
    return sql;
}

From source file:com.theaigames.game.warlight2.MapCreator.java

/**
 * @param map/*from   w w w . jav  a 2s .com*/
 * @return : the string representation of how given map's regions are connected
 */
private static String getNeighborsString(Map map) {
    String neighborsString = "setup_map neighbors";
    ArrayList<Point> doneList = new ArrayList<Point>();
    for (Region region : map.regions) {
        int id = region.getId();
        String neighbors = "";
        for (Region neighbor : region.getNeighbors()) {
            if (checkDoneList(doneList, id, neighbor.getId())) {
                neighbors = neighbors.concat("," + neighbor.getId());
                doneList.add(new Point(id, neighbor.getId()));
            }
        }
        if (neighbors.length() != 0) {
            neighbors = neighbors.replaceFirst(",", " ");
            neighborsString = neighborsString.concat(" " + id + neighbors);
        }
    }
    return neighborsString;
}

From source file:com.runwaysdk.generation.loader.RunwayClassLoader.java

/**
 * Loads an array from the base component up. If an array is loaded without
 * its componentType already loaded then an error occurs. Thus it loads from
 * inside out./*from w ww. j  av  a  2  s. co m*/
 * 
 * @param arrayType
 */
public static Class<?> loadArray(String arrayType) {
    // Keep track of what types of array we have (an array of Integers and an
    // array of
    // Business objects, for example)
    Stack<String> baseTypes = new Stack<String>();
    String baseType = arrayType;

    Class<?> arrayClass = null;

    // This loop strips the base type out of any n-dimensional array
    while (arrayPattern.matcher(baseType).matches()) {
        if (arrayPrefix.matcher(baseType).matches()) {
            baseType = baseType.replaceFirst("\\[L", "").replace(";", "").trim();
        } else {
            baseType = baseType.replaceFirst("\\[", "");
        }
        // Add the base type to the stack
        baseTypes.push(baseType);
    }

    // We must load all base types before we can try to load arrays of those
    // types
    while (!baseTypes.isEmpty()) {
        String type = baseTypes.pop();
        Class<?> componentType;
        componentType = LoaderDecorator.load(type);
        arrayClass = Array.newInstance(componentType, 0).getClass();
    }
    return arrayClass;
}

From source file:com.datasalt.pangool.solr.SolrRecordWriter.java

static String relativePathForZipEntry(final String rawPath, final String baseName, final String root) {
    String relativePath = rawPath.replaceFirst(Pattern.quote(root.toString()), "");
    LOG.info(/*from   ww  w  . j  a va2s.c  om*/
            String.format("RawPath %s, baseName %s, root %s, first %s", rawPath, baseName, root, relativePath));

    if (relativePath.startsWith(Path.SEPARATOR)) {
        relativePath = relativePath.substring(1);
    }
    LOG.info(String.format("RawPath %s, baseName %s, root %s, post leading slash %s", rawPath, baseName, root,
            relativePath));
    if (relativePath.isEmpty()) {
        LOG.warn(String.format("No data after root (%s) removal from raw path %s", root, rawPath));
        return baseName;
    }
    // Construct the path that will be written to the zip file, including
    // removing any leading '/' characters
    String inZipPath = baseName + Path.SEPARATOR_CHAR + relativePath;

    LOG.info(String.format("RawPath %s, baseName %s, root %s, inZip 1 %s", rawPath, baseName, root, inZipPath));
    if (inZipPath.startsWith(Path.SEPARATOR)) {
        inZipPath = inZipPath.substring(1);
    }
    LOG.info(String.format("RawPath %s, baseName %s, root %s, inZip 2 %s", rawPath, baseName, root, inZipPath));

    return inZipPath;

}

From source file:eu.eubrazilcc.lvl.core.util.UrlUtils.java

/**
 * Parses a URL from a String. This method supports file-system paths 
 * (e.g. /foo/bar)./*  w ww.j  a v a2 s . com*/
 * @param str - String representation of an URL
 * @return an URL.
 * @throws IOException If an input/output error occurs.
 */
public static @Nullable URL parseURL(final String str) throws MalformedURLException {
    URL url = null;
    if (isNotBlank(str)) {
        try {
            url = new URL(str);
        } catch (MalformedURLException e) {
            url = null;
            if (!str.matches("^[a-zA-Z]+[/]*:[^\\\\]")) {
                // convert path to UNIX path
                String path = separatorsToUnix(str.trim());
                final Pattern pattern = Pattern.compile("^([a-zA-Z]:/)");
                final Matcher matcher = pattern.matcher(path);
                path = matcher.replaceFirst("/");
                // convert relative paths to absolute paths
                if (!path.startsWith("/")) {
                    path = path.startsWith("~") ? path.replaceFirst("~", System.getProperty("user.home"))
                            : concat(System.getProperty("user.dir"), path);
                }
                // normalize path
                path = normalize(path, true);
                if (isNotBlank(path)) {
                    url = new File(path).toURI().toURL();
                } else {
                    throw new MalformedURLException("Invalid path: " + path);
                }
            } else {
                throw e;
            }
        }
    }
    return url;
}

From source file:org.apereo.services.persondir.support.web.RequestAttributeSourceFilter.java

private static List<Object> splitOnSemiColonHandlingBackslashEscaping(final String in) {
    final List<Object> result = new LinkedList<>();

    int i = 1;/*from ww w. j  av a  2 s  . c om*/
    String prefix = "";
    final String[] splitStringArr = in.split(";");
    for (final String s : splitStringArr) {
        final String s2 = s.replaceFirst("\\\\$", ";");
        if (s.equals(s2) || i == splitStringArr.length) {
            result.add(prefix + s2);
            prefix = "";
        } else {
            prefix += s2;
        }
        i++;
    }
    return result;
}