Example usage for java.lang Character isDigit

List of usage examples for java.lang Character isDigit

Introduction

In this page you can find the example usage for java.lang Character isDigit.

Prototype

public static boolean isDigit(int codePoint) 

Source Link

Document

Determines if the specified character (Unicode code point) is a digit.

Usage

From source file:com.odiago.flumebase.io.CharBufferUtils.java

/**
 * Parses a CharSequence into a long in base 10.
 *///from  w  ww. j a  v a  2  s  . com
public static long parseLong(CharBuffer chars) throws ColumnParseException {
    long result = 0L;

    final int limit = chars.limit();
    final int start = chars.position();
    if (0 == limit - start) {
        // The empty string can not be parsed as an integer.
        throw new ColumnParseException("No value provided");
    }

    boolean isNegative = false;
    for (int pos = start; pos < limit; pos++) {
        char cur = chars.get();
        if (pos == start && cur == '-') {
            isNegative = true;
            if (limit - start == 1) {
                // "-" is not an integer we accept.
                throw new ColumnParseException("No integer part provided");
            }
        } else if (Character.isDigit(cur)) {
            byte digitVal = (byte) (cur - '0');
            result = result * 10 - digitVal;
            // TODO: Detect over/underflow and signal exception?
        } else {
            throw new ColumnParseException("Invalid character in number");
        }
    }

    // We built up the value as a negative, to use the larger "half" of the
    // integer range. If it's not negative, flip it on return.
    return isNegative ? result : -result;
}

From source file:StringUtils.java

/**
 * Parse textual representation of fraction to a floating point number
 * /*from   w  w w  .j av  a2  s. c  o  m*/
 * @param textToParse -
 *          in the form "any_text whole_part quotient/divisor any_text"
 * @param defaultValue -
 *          if the test is unparsable, what default value to return
 * @param bIgnoreRest -
 *          if true, this will ignore the rest of the string (any_other_text)
 *          after the fraction, if false then the whole string is considered
 * @return double - number coresponding to the fraction
 */
public static double parseFraction(String textToParse, double defaultValue, boolean bIgnoreRest) {
    double parsed = defaultValue;
    int iLength;
    int iIndex;
    int iIndexStart;
    int iIndexEnd;
    int iNumber;

    // lets use "xxxxxxx 123 456 / 789 yyyyy" as example or
    // lets use "xxxxxxx 123 / 789 yyyyy" as example

    iIndexStart = 0;
    iLength = textToParse.length();
    if (bIgnoreRest) {
        // Skip while not number
        while ((iIndexStart < iLength) && (!Character.isDigit(textToParse.charAt(iIndexStart)))) {
            iIndexStart++;
        }
        // We skiped "xxxxxxx", iIndexStart is at "123 456 / 789 yyyyy"
    }

    // We should be at first digit
    if (iIndexStart < iLength) {
        // Find end of the number
        iIndex = iIndexStart;
        while ((iIndex < iLength) && (Character.isDigit(textToParse.charAt(iIndex)))) {
            iIndex++;
        }
        iIndexEnd = iIndex;
        // We skiped "123", iIndexStart is at "123 456 / 789 yyyyy"
        // iIndexEnd is at " 456 / 789 yyyyy"

        if (iIndexStart != iIndexEnd) {
            // There was at least some digits
            iNumber = Integer.parseInt(textToParse.substring(iIndexStart, iIndexEnd));
            // iNumber is 123

            // There was at least one digit, now is it whole part or quotient?
            // Skip spaces
            while ((iIndex < iLength)
                    && ((textToParse.charAt(iIndex) == ' ') || (textToParse.charAt(iIndex) == '-'))) {
                iIndex++;
            }
            // We skiped "123", iIndex is at "456 / 789 yyyyy"

            // Now we have stopped because of 2 things, we either reached end of
            // string or we have found something other than space, if it is /
            // then it was qoutient, if it is digit, then it was whole part
            if (iIndex == iLength) {
                // it was a whole part and we are done
                parsed = iNumber;
            } else {
                int iQuotient = 0;
                int iDivisor = Integer.MAX_VALUE;

                if (Character.isDigit(textToParse.charAt(iIndex))) {
                    int iWholePart = 0;

                    // it was a whole part and we continue to look for the quotient
                    iWholePart = iNumber;

                    // Find end of the number
                    iIndexStart = iIndex; // Remember start
                    while ((iIndex < iLength) && (Character.isDigit(textToParse.charAt(iIndex)))) {
                        iIndex++;
                    }
                    iIndexEnd = iIndex;
                    // We skiped "456", iStartIndex is at "456 / 789 yyyyy"
                    // And iIndexEnd is at " / 789 yyyyy"

                    iQuotient = Integer.parseInt(textToParse.substring(iIndexStart, iIndexEnd));
                    // iQuotient is 456

                    // Skip spaces
                    while ((iIndex < iLength) && (textToParse.charAt(iIndex) == ' ')) {
                        iIndex++;
                    }
                    // And iIndex is at "/ 789 yyyyy"

                    if (textToParse.charAt(iIndex) == '/') {
                        // It was a quotient and we continue to look for divisor

                        iIndexStart = iIndex + 1;
                        while ((iIndexStart < iLength) && (textToParse.charAt(iIndexStart) == ' ')) {
                            iIndexStart++;
                        }
                        // And iIndexStart is at "789 yyyyy"

                        // We should be at next digit
                        if (iIndexStart < iLength) {
                            // Find end of the number
                            iIndex = iIndexStart;
                            while ((iIndex < iLength) && (Character.isDigit(textToParse.charAt(iIndex)))) {
                                iIndex++;
                            }
                            iIndexEnd = iIndex;
                            // We skiped "789", iStartIndex is at "789 yyyyy"
                            // And iIndexEnd is at " yyyyy"

                            if (iIndexStart != iIndexEnd) {
                                iDivisor = Integer.parseInt(textToParse.substring(iIndexStart, iIndexEnd));
                                // iDivisor is 789
                                if (iDivisor != 0) {
                                    if (iIndexEnd == iLength) {
                                        // And we are at the end of the string
                                        parsed = ((double) (iWholePart))
                                                + (((double) iQuotient) / ((double) iDivisor));
                                    } else {
                                        if (bIgnoreRest) {
                                            // And we can ignore what is after
                                            parsed = ((double) (iWholePart))
                                                    + (((double) iQuotient) / ((double) iDivisor));
                                        } else {
                                            // there was something else we don't know what so
                                            // return the default value
                                        }
                                    }
                                }
                            } else {
                                // The divisor is missing, return default value
                            }
                        } else {
                            // The divisor is missing, return default value
                        }
                    } else {
                        // The divisor is missing, return default value
                    }
                } else {
                    if (textToParse.charAt(iIndex) == '/') {
                        // And iIndex is at "/ 456 yyyyy"

                        // It was a quotient and we continue to look for divisor
                        iQuotient = iNumber;
                        // iQuotient is 123

                        iIndexStart = iIndex + 1;
                        while ((iIndexStart < iLength) && (textToParse.charAt(iIndexStart) == ' ')) {
                            iIndexStart++;
                        }
                        // And iIndexStart is at "456 yyyyy"

                        // We should be at next digit
                        if (iIndexStart < iLength) {
                            // Find end of the number
                            iIndex = iIndexStart;
                            while ((iIndex < iLength) && (Character.isDigit(textToParse.charAt(iIndex)))) {
                                iIndex++;
                            }
                            iIndexEnd = iIndex;
                            // We skipped "456", iIndexStart is at "456 yyyyy"
                            // iIndexEnd is at " yyyyy"

                            if (iIndexStart != iIndexEnd) {
                                iDivisor = Integer.parseInt(textToParse.substring(iIndexStart, iIndexEnd));
                                // iDivisor is 456

                                if (iDivisor != 0) {
                                    if (iIndexEnd == iLength) {
                                        // And we are at the end of the string
                                        parsed = ((double) iQuotient) / ((double) iDivisor);
                                    } else {
                                        if (bIgnoreRest) {
                                            // And we can ignore what is after
                                            parsed = ((double) iQuotient) / ((double) iDivisor);
                                        } else {
                                            // there was something else we don't know what so
                                            // return the default value
                                        }
                                    }
                                }
                            } else {
                                // The divisor is missing, return default value
                            }
                        } else {
                            // The divisor is missing, return default value
                        }
                    } else {
                        // It was a whole part and there is something else
                        if (bIgnoreRest) {
                            // and we are done
                            parsed = iNumber;
                        } else {
                            // there was something else we don't know what so
                            // return the default value
                        }
                    }
                }
            }
        }
    }

    return parsed;
}

From source file:de.alpharogroup.string.StringExtensions.java

/**
 * Checks if the given String is an Number.
 *
 * @param testString// w ww  .j a v  a2  s  . c  o  m
 *            The String to check.
 * @return true if the given String is a number otherwise false.
 */
public static final boolean isNumber(final String testString) {
    if (null == testString) {
        return false;
    }
    for (int i = 0; i < testString.length(); i++) {
        if (Character.isDigit(testString.charAt(i)) == false) {
            return false;
        }
    }
    return true;
}

From source file:com.ikanow.infinit.e.harvest.utils.DateUtility.java

public synchronized static long parseDate(String sDate) {
    if (null == _allowedDatesArray_startsWithLetter) {
        _allowedDatesArray_startsWithLetter = new String[] { DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern(),

                "MMM d, yyyy hh:mm a", "MMM d, yyyy HH:mm", "MMM d, yyyy hh:mm:ss a", "MMM d, yyyy HH:mm:ss",
                "MMM d, yyyy hh:mm:ss.SS a", "MMM d, yyyy HH:mm:ss.SS",

                "EEE MMM dd HH:mm:ss zzz yyyy", "EEE MMM dd yyyy HH:mm:ss zzz",
                "EEE MMM dd yyyy HH:mm:ss 'GMT'Z (zzz)", };
        _allowedDatesArray_numeric_1 = new String[] { "yyyy-MM-dd'T'HH:mm:ss'Z'",
                DateFormatUtils.ISO_DATE_FORMAT.getPattern(),
                DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.getPattern(),
                DateFormatUtils.ISO_DATETIME_FORMAT.getPattern(),
                DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern() };

        _allowedDatesArray_numeric_2 = new String[] { "yyyyMMdd", "yyyyMMdd hh:mm a", "yyyyMMdd HH:mm",
                "yyyyMMdd hh:mm:ss a", "yyyyMMdd HH:mm:ss", "yyyyMMdd hh:mm:ss.SS a", "yyyyMMdd HH:mm:ss.SS",
                // Julian, these are unlikely
                "yyyyDDD", "yyyyDDD hh:mm a", "yyyyDDD HH:mm", "yyyyDDD hh:mm:ss a", "yyyyDDD HH:mm:ss",
                "yyyyDDD hh:mm:ss.SS a", "yyyyDDD HH:mm:ss.SS", };
        _allowedDatesArray_stringMonth = new String[] { "dd MMM yy", "dd MMM yy hh:mm a", "dd MMM yy HH:mm",
                "dd MMM yy hh:mm:ss a", "dd MMM yy HH:mm:ss", "dd MMM yy hh:mm:ss.SS a",
                "dd MMM yy HH:mm:ss.SS", };
        _allowedDatesArray_numericMonth = new String[] { "MM dd yy", "MM dd yy hh:mm a", "MM dd yy HH:mm",
                "MM dd yy hh:mm:ss a", "MM dd yy HH:mm:ss", "MM dd yy hh:mm:ss.SS a", "MM dd yy HH:mm:ss.SS", };
    }//  ww w  .  j av  a 2s.com

    // Starts with day or month:

    String sDateTmp = sDate;
    if (Character.isLetter(sDate.charAt(0))) {
        try {
            Date date = DateUtils.parseDate(sDate, _allowedDatesArray_startsWithLetter);
            return date.getTime();
        } catch (Exception e) {
        } // keep going         
    } //TESTED
    else if (Character.isLetter(sDate.charAt(5))) {

        // month must be string, doesn't start with day though

        try {
            int index = sDate.indexOf(':');
            if (index > 0) {
                sDate = new StringBuffer(sDate.substring(0, index).replaceAll("[./-]", " "))
                        .append(sDate.substring(index)).toString();
            } else {
                sDate = sDate.replaceAll("[ ./-]", " ");
            }
            Date date = DateUtils.parseDate(sDate, _allowedDatesArray_stringMonth);
            return date.getTime();
        } catch (Exception e) {
        } // keep going                              
    } //TESTED
    else {

        // Starts with a number most likely...

        int n = 0;
        for (; n < 4; ++n) {
            if (!Character.isDigit(sDate.charAt(n))) {
                break;
            }
        }
        if (4 == n) {

            // (Probably starts with a year)            

            // One of the formal formats starting with a year            

            try {
                Date date = DateUtils.parseDate(sDate, _allowedDatesArray_numeric_1);
                return date.getTime();
            } catch (Exception e) {
            } // keep going

            // Something more ad hoc starting with a year                        

            try {
                int index = sDate.indexOf(':');
                if (index > 0) {
                    sDate = new StringBuffer(sDate.substring(0, index).replace("-", ""))
                            .append(sDate.substring(index)).toString();
                } else {
                    sDate = sDate.replace("-", "");
                }
                Date date = DateUtils.parseDate(sDate, _allowedDatesArray_numeric_2);
                return date.getTime();
            } catch (Exception e) {
            } // keep going                     
        } //TESTED

        // Probably starts with a day         

        try {
            int index = sDate.indexOf(':');
            if (index > 0) {
                sDate = new StringBuffer(sDate.substring(0, index).replaceAll("[./-]", " "))
                        .append(sDate.substring(index)).toString();
            } else {
                sDate = sDate.replaceAll("[./-]", " ");
            }
            Date date = DateUtils.parseDate(sDate, _allowedDatesArray_numericMonth);
            return date.getTime();
        } //TESTED
        catch (Exception e) {
        } // keep going                     

    }
    sDate = sDateTmp;

    // If we're here, nothing's worked, try "natural language processing"

    try {
        return Chronic.parse(sDate).getBeginCalendar().getTime().getTime();
    } //TESTED
    catch (Exception e2) {
        // Error all the way out
        throw new RuntimeException("Can't parse: " + sDate);
    } //TESTED
}

From source file:de.jfachwert.post.Adresse.java

/**
 * Validiert die uebergebene Adresse auf moegliche Fehler.
 *
 * @param ort        der Ort//from   w w w.  ja  v a 2  s  .c om
 * @param strasse    die Strasse
 * @param hausnummer die Hausnummer
 */
public static void validate(Ort ort, String strasse, String hausnummer) {
    if (!ort.getPLZ().isPresent()) {
        throw new InvalidValueException(ort, "postal_code");
    }
    if (StringUtils.isBlank(strasse)) {
        throw new InvalidValueException(strasse, "street");
    }
    if (StringUtils.isBlank(hausnummer)) {
        throw new InvalidValueException(hausnummer, "house_number");
    }
    if (Character.isDigit(strasse.trim().charAt(0)) && (Character.isLetter(hausnummer.trim().charAt(0)))
            && (strasse.length() < hausnummer.length())) {
        throw new InvalidValueException(strasse + " " + hausnummer, "values_exchanged");
    }
}

From source file:com.oakhole.utils.EncodeUtils.java

/**
 * jsescape.//from   w w  w .  ja  v  a2  s  .  c  o m
 * 
 * @param src
 *            String
 * @return String
 */
public static String escapeJS(String src) {
    int i;
    char j;
    StringBuffer tmp = new StringBuffer();
    tmp.ensureCapacity(src.length() * UNICODE_LENGTH);

    for (i = 0; i < src.length(); i++) {
        j = src.charAt(i);

        if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j)) {
            tmp.append(j);
        } else if (j < ANSI_CHAR_CODE) {
            tmp.append("%");

            if (j < UNPRINTABLE_CHAR_CODE) {
                tmp.append("0");
            }

            tmp.append(Integer.toString(j, HEX));
        } else {
            tmp.append("%u");
            tmp.append(Integer.toString(j, HEX));
        }
    }

    return tmp.toString();
}

From source file:com.pfarrell.utils.misc.TextTools.java

/**
 * make a string with only digits/*from  w w w. ja v  a 2s .c o m*/
 * @param arg  string
 * @return string with only digits
 */
public static String justDigits(String arg) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < arg.length(); i++) {
        int c = arg.codePointAt(i);
        if (Character.isDigit(c)) {
            sb.appendCodePoint(c);
        }
    }
    return sb.toString();
}

From source file:com.predic8.membrane.core.interceptor.IndexInterceptor.java

static String fullfillRegexp(String regex) {
    StringBuilder sb = new StringBuilder();
    int p = 0, groupLevel = 0;
    WHILE: while (p < regex.length()) {
        int c = regex.codePointAt(p++);
        switch (c) {
        case '\\':
            if (p == regex.length())
                return null; // illegal
            c = regex.codePointAt(p++);/*from ww w. j av a2 s .  c om*/
            if (Character.isDigit(c))
                return null; // backreferences are not supported
            if (c == 'Q') {
                while (true) {
                    if (p == regex.length())
                        return null; // 'end of regex' within quote
                    c = regex.codePointAt(p++);
                    if (c == '\\') {
                        if (p == regex.length())
                            return null; // 'end of regex' within quote
                        c = regex.codePointAt(p++);
                        if (c == 'E')
                            break;
                        sb.append('\\');
                    }
                    sb.appendCodePoint(c);
                }
                break;
            }
            if (c == 'E') {
                return null; // 'end of quote' without begin
            }
            sb.appendCodePoint(c);
            break;
        case '[':
        case '?':
        case '*':
        case '+':
        case '{':
            return null; // meaningful characters we do not unterstand
        case '(':
            groupLevel++;
            break;
        case ')':
            if (groupLevel == 0)
                return null; // unbalanced ')'
            else
                groupLevel--;
            break;
        case '|':
            if (groupLevel == 0) {
                break WHILE;
            }
            W2: while (true) {
                if (++p == regex.length())
                    return null; // unbalanced ')'
                switch (regex.charAt(p)) {
                case ')':
                    break W2;
                case '[':
                case '?':
                case '*':
                case '+':
                case '{':
                    return null; // meaningful characters we do not unterstand
                case '\\':
                    return null; // TODO: \) \Q..\E
                }
            }
            groupLevel--;
            p++;
            break;
        case '^':
            if (p == 1)
                break;
            return null;
        case '$':
            if (p == regex.length() || regex.codePointAt(p) == '|')
                break;
            return null;
        case '.':
            int q;
            if (p != regex.length() && isQuantifier(q = regex.codePointAt(p))) {
                if (++p != regex.length() && isModifier(regex.codePointAt(p)))
                    p++;
                if (q == '+')
                    sb.append('a');
            } else {
                sb.append('a');
            }
            break;
        default:
            sb.appendCodePoint(c);
            break;
        }
    }
    if (groupLevel > 0)
        return null;
    return sb.toString();
}

From source file:com.jkoolcloud.tnt4j.streams.utils.SyslogUtils.java

/**
 * Test key value pair for numeric, convert and store in map.
 *
 * @param map//from   w w w. jav a 2  s  . c o  m
 *            collection of name, value pairs
 * @param key
 *            associated with key, value pair
 * @param value
 *            associated with key, value pair
 */
private static void mapToTyped(Map<String, Object> map, String key, String value) {
    Number num = null;
    if (StringUtils.isNotEmpty(value) && Character.isDigit(value.charAt(0))) {
        try {
            num = Long.valueOf(value);
        } catch (Exception el) {
            try {
                num = Double.valueOf(value);
            } catch (Exception ed) {
            }
        }
    }

    map.put(key, num == null ? value : num);
}

From source file:edu.chalmers.dat076.moviefinder.service.TitleParser.java

private TemporaryMedia getInformation(StringBuilder mySb) {

    TemporaryMedia returnMedia = new TemporaryMedia();
    StringBuilder wordSb = new StringBuilder();

    int tmpYear;//w  w w.  j  a v  a  2s .c  o  m
    int year = -1;
    int thisYear = Calendar.getInstance().get(Calendar.YEAR);

    boolean deleteYear = false;
    boolean finalWord = true;

    for (int i = 0; i < mySb.length(); i++) {
        if (mySb.charAt(i) == '.' || mySb.charAt(i) == ' ' || mySb.charAt(i) == '-' || mySb.charAt(i) == '_') {

            if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
                mySb.delete(i - (wordSb.length() + 1), mySb.length());
                finalWord = false;
                // final useful word found. No point in continuing.
                break;
            }
            mySb.replace(i, i + 1, " ");

            tmpYear = checkForYear(wordSb);
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = true;
            }
            wordSb.setLength(0);

        } else if (wordSb.length() == 0
                && (mySb.charAt(i) == 'S' || mySb.charAt(i) == 's' || Character.isDigit(mySb.charAt(i)))) {
            // See if new word contains series and episode information.

            StringBuilder whatsLeft = new StringBuilder(mySb.subSequence(i, mySb.length()));
            if (getEpisodePotential(whatsLeft)) {
                TemporaryMedia tmpMedia = getEpisodeInfo(whatsLeft);
                returnMedia.setIsMovie(false);
                returnMedia.setSeason(tmpMedia.getSeason());
                returnMedia.setEpisode(tmpMedia.getEpisode());
                mySb.delete(i, mySb.length());
                // series and episode information saved. No point in continuing.
                break;

            } else {
                wordSb.append(mySb.charAt(i));
            }
        } else if (mySb.charAt(i) == '[' || mySb.charAt(i) == '(') {
            // Brackets shoudl usually be removed. They could possibly contain realease year.

            if (Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
                mySb.delete(i - (wordSb.length() + 1), mySb.length());
                finalWord = false;
                // final useful word found. No point in continuing.
                break;
            }
            tmpYear = checkForYear(wordSb);
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = true;
            }
            wordSb.setLength(0);

            if (mySb.charAt(i) == '[') {
                tmpYear = removeUntil(mySb, i, ']');
            } else if (mySb.charAt(i) == '(') {
                tmpYear = removeUntil(mySb, i, ')');
            }
            if (tmpYear > 1900 && tmpYear <= thisYear) {
                year = tmpYear;
                deleteYear = false;
            }
            i--; // Need to compensate for removing bracket.

        } else {
            // Nothing useful here. Save the char and continue.
            wordSb.append(mySb.charAt(i));
        }
    }

    if (finalWord && Constants.MOVIE_FILE_ENDING_WORDS.contains(wordSb.toString())) {
        mySb.delete(mySb.length() - wordSb.length(), mySb.length());
    } else {
        tmpYear = checkForYear(wordSb);
        if (tmpYear > 1900 && tmpYear <= thisYear) {
            year = tmpYear;
            deleteYear = true;
        }
    }
    if (deleteYear && returnMedia.IsMovie()) {
        int i = mySb.lastIndexOf(year + "");
        mySb.delete(i, i + 4);
    }

    returnMedia.setYear(year);
    returnMedia.setName(mySb.toString().trim());

    return returnMedia;
}