public static String getDirectoryName(String path) { if (path != null) { int index = path.lastIndexOf(DIRECTORY_SEPARATOR_CHAR); int index2 = path.lastIndexOf(ALT_DIRECTORY_SEPARATOR_CHAR); if (index2 > index) { index = index2; } if (index != -1) { if (index == path.length() - 1) { if (path.indexOf(VOLUME_SEPARATOR_CHAR) == index - 1) { return null; } else { path = path.substring(0, index); } } else { if (path.indexOf(VOLUME_SEPARATOR_CHAR) == index - 1) { path = path.substring(0, index + 1); } else { path = path.substring(0, index); } } if (path.length() == 2 && path[1] == VOLUME_SEPARATOR_CHAR) { return ""; } } return path; } return null; }
/** * Attempts to extract a match from a {@code candidate} character sequence. * * @param candidate the candidate text that might contain a phone number * @param offset the offset of {@code candidate} within {@link #text} * @return the match found, null if none can be found */ private PhoneNumberMatch extractMatch(CharSequence candidate, int offset) { // Skip a match that is more likely a publication page reference or a date. if (PUB_PAGES.matcher(candidate).find() || SLASH_SEPARATED_DATES.matcher(candidate).find()) { return(null); } // Skip potential time-stamps. if (TIME_STAMPS.matcher(candidate).find()) { String followingText = text.toString().substring(offset + candidate.length()); if (TIME_STAMPS_SUFFIX.matcher(followingText).lookingAt()) { return(null); } } // Try to come up with a valid match given the entire candidate. String rawString = candidate.toString(); PhoneNumberMatch match = parseAndVerify(rawString, offset); if (match != null) { return(match); } // If that failed, try to find an "inner match" - there might be a phone number within this // candidate. return(extractInnerMatch(rawString, offset)); }
/** * Helper method to get the national-number part of a number, formatted without any national * prefix, and return it as a set of digit blocks that would be formatted together. */ private static String[] getNationalNumberGroups(PhoneNumberUtil util, PhoneNumber number, NumberFormat formattingPattern) { if (formattingPattern == null) { // This will be in the format +CC-DG;ext=EXT where DG represents groups of digits. String rfc3966Format = util.format(number, PhoneNumberFormat.RFC3966); // We remove the extension part from the formatted string before splitting it into different // groups. int endIndex = rfc3966Format.indexOf(';'); if (endIndex < 0) { endIndex = rfc3966Format.length(); } // The country-code will have a '-' following it. int startIndex = rfc3966Format.indexOf('-') + 1; return(rfc3966Format.substring(startIndex, endIndex).split("-")); } else { // We format the NSN only, and split that according to the separator. String nationalSignificantNumber = util.getNationalSignificantNumber(number); return(util.formatNsnUsingPattern(nationalSignificantNumber, formattingPattern, PhoneNumberFormat.RFC3966).split("-")); } }
private void appendSubsequentLocalePart(String subsequentLocalePart, StringBuilder fullLocale) { if (subsequentLocalePart.length() > 0) { fullLocale.append('_').append(subsequentLocalePart); } }
/** * Gets the name of the file that contains the mapping data for the {@code countryCallingCode} in * the language specified. * * @param countryCallingCode the country calling code of phone numbers which the data file * contains * @param language two-letter lowercase ISO language codes as defined by ISO 639-1 * @param script four-letter titlecase (the first letter is uppercase and the rest of the letters * are lowercase) ISO script codes as defined in ISO 15924 * @param region two-letter uppercase ISO country codes as defined by ISO 3166-1 * @return the name of the file, or empty string if no such file can be found */ internal String getFileName(int countryCallingCode, String language, String script, String region) { if (language.length() == 0) { return(""); } int index = Arrays.binarySearch(countryCallingCodes, countryCallingCode); if (index < 0) { return(""); } Set <String> setOfLangs = availableLanguages.get(index); if (setOfLangs.size() > 0) { String languageCode = findBestMatchingLanguageCode(setOfLangs, language, script, region); if (languageCode.length() > 0) { StringBuilder fileName = new StringBuilder(); fileName.append(countryCallingCode).append('_').append(languageCode); return(fileName.toString()); } } return(""); }
private boolean createFormattingTemplate(NumberFormat format) { String numberPattern = format.getPattern(); // The formatter doesn't format numbers when numberPattern contains "|", e.g. // (20|3)\d{4}. In those cases we quickly return. if (numberPattern.indexOf('|') != -1) { return(false); } // Replace anything in the form of [..] with \d numberPattern = CHARACTER_CLASS_PATTERN.matcher(numberPattern).replaceAll("\\\\d"); // Replace any standalone digit (not the one in d{}) with \d numberPattern = STANDALONE_DIGIT_PATTERN.matcher(numberPattern).replaceAll("\\\\d"); formattingTemplate.setLength(0); String tempTemplate = getFormattingTemplate(numberPattern, format.getFormat()); if (tempTemplate.length() > 0) { formattingTemplate.append(tempTemplate); return(true); } return(false); }
/** * Attempts to find the next subsequence in the searched sequence on or after {@code searchIndex} * that represents a phone number. Returns the next match, null if none was found. * * @param index the search index to start searching at * @return the phone number match found, null if none can be found */ private PhoneNumberMatch find(int index) { Matcher matcher = PATTERN.matcher(text); while ((maxTries > 0) && matcher.find(index)) { int start = matcher.start(); CharSequence candidate = text.subSequence(start, matcher.end()); // Check for extra numbers at the end. // TODO: This is the place to start when trying to support extraction of multiple phone number // from split notations (+41 79 123 45 67 / 68). candidate = trimAfterFirstMatch(PhoneNumberUtil.SECOND_NUMBER_START_PATTERN, candidate); PhoneNumberMatch match = extractMatch(candidate, start); if (match != null) { return(match); } index = start + candidate.length(); maxTries--; } return(null); }
/** * Returns the description of the geographical area the {@code number} corresponds to. This method * distinguishes the case of an invalid prefix and a prefix for which the name is not available in * the current language. If the description is not available in the current language an empty * string is returned. If no description was found for the provided number, null is returned. * * @param number the phone number to look up * @return the description of the geographical area */ internal String lookup(PhoneNumber number) { int numOfEntries = areaCodeMapStorage.getNumOfEntries(); if (numOfEntries == 0) { return(null); } long phonePrefix = Long.parseLong(number.getCountryCode() + phoneUtil.getNationalSignificantNumber(number)); int currentIndex = numOfEntries - 1; SortedSet <Integer> currentSetOfLengths = areaCodeMapStorage.getPossibleLengths(); while (currentSetOfLengths.size() > 0) { Integer possibleLength = currentSetOfLengths.last(); String phonePrefixStr = String.valueOf(phonePrefix); if (phonePrefixStr.length() > possibleLength) { phonePrefix = Long.parseLong(phonePrefixStr.substring(0, possibleLength)); } currentIndex = binarySearch(0, currentIndex, phonePrefix); if (currentIndex < 0) { return(null); } int currentPrefix = areaCodeMapStorage.getPrefix(currentIndex); if (phonePrefix == currentPrefix) { return(areaCodeMapStorage.getDescription(currentIndex)); } currentSetOfLengths = currentSetOfLengths.headSet(possibleLength); } return(null); }
internal static boolean containsOnlyValidXChars( PhoneNumber number, String candidate, PhoneNumberUtil util) { // The characters 'x' and 'X' can be (1) a carrier code, in which case they always precede the // national significant number or (2) an extension sign, in which case they always precede the // extension number. We assume a carrier code is more than 1 digit, so the first case has to // have more than 1 consecutive 'x' or 'X', whereas the second case can only have exactly 1 'x' // or 'X'. We ignore the character if it appears as the last character of the string. for (int index = 0; index < candidate.length() - 1; index++) { char charAtIndex = candidate.charAt(index); if (charAtIndex == 'x' || charAtIndex == 'X') { char charAtNextIndex = candidate.charAt(index + 1); if (charAtNextIndex == 'x' || charAtNextIndex == 'X') { // This is the carrier code case, in which the 'X's always precede the national // significant number. index++; if (util.isNumberMatch(number, candidate.substring(index)) != MatchType.NSN_MATCH) { return(false); } // This is the extension sign case, in which the 'x' or 'X' should always precede the // extension number. } else if (!PhoneNumberUtil.normalizeDigitsOnly(candidate.substring(index)).equals( number.getExtension())) { return(false); } } } return(true); }
/* public void writeFloat(float v) { writeInt(Float.floatToIntBits(v)); } public void writeDouble(double v) { writeLong(Double.doubleToLongBits(v)); } */ public void writeBytes(String s) { int len = s.length(); for (int i = 0 ; i < len ; i++) { @out.write((byte)s.charAt(i)); } incCount(len); }
/* * public void writeFloat(float v) { * writeInt(Float.floatToIntBits(v)); * } * public void writeDouble(double v) { * writeLong(Double.doubleToLongBits(v)); * } */ public void writeBytes(String s) { int len = s.length(); for (int i = 0; i < len; i++) { @out.write((byte)s.charAt(i)); } incCount(len); }
public void writeChars(String s) { int len = s.length(); for (int i = 0; i < len; i++) { int v = s.charAt(i); @out.write((int)(((uint)v) >> 8) & 0xFF); @out.write((int)(((uint)v) >> 0) & 0xFF); } incCount(len * 2); }
/** * Parses a phone number from the {@code candidate} using {@link PhoneNumberUtil#parse} and * verifies it matches the requested {@link #leniency}. If parsing and verification succeed, a * corresponding {@link PhoneNumberMatch} is returned, otherwise this method returns null. * * @param candidate the candidate match * @param offset the offset of {@code candidate} within {@link #text} * @return the parsed and validated phone number match, or null */ private PhoneNumberMatch parseAndVerify(String candidate, int offset) { try { // Check the candidate doesn't contain any formatting which would indicate that it really // isn't a phone number. if (!MATCHING_BRACKETS.matcher(candidate).matches()) { return(null); } // If leniency is set to VALID or stricter, we also want to skip numbers that are surrounded // by Latin alphabetic characters, to skip cases like abc8005001234 or 8005001234def. if (leniency.compareTo(Leniency.VALID) >= 0) { // If the candidate is not at the start of the text, and does not start with phone-number // punctuation, check the previous character. if (offset > 0 && !LEAD_CLASS.matcher(candidate).lookingAt()) { char previousChar = text.charAt(offset - 1); // We return null if it is a latin letter or an invalid punctuation symbol. if (isInvalidPunctuationSymbol(previousChar) || isLatinLetter(previousChar)) { return(null); } } int lastCharIndex = offset + candidate.length(); if (lastCharIndex < text.length()) { char nextChar = text.charAt(lastCharIndex); if (isInvalidPunctuationSymbol(nextChar) || isLatinLetter(nextChar)) { return(null); } } } PhoneNumber number = phoneUtil.parseAndKeepRawInput(candidate, preferredRegion); if (leniency.verify(number, candidate, phoneUtil)) { // We used parseAndKeepRawInput to create this number, but for now we don't return the extra // values parsed. TODO: stop clearing all values here and switch all users over // to using rawInput() rather than the rawString() of PhoneNumberMatch. number.clearCountryCodeSource(); number.clearRawInput(); number.clearPreferredDomesticCarrierCode(); return(new PhoneNumberMatch(offset, candidate, number)); } } catch (NumberParseException) { // ignore and continue } return(null); }
public static String quoteReplacement(String s) { if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1)) return s; StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c == '\\' || c == '$') { sb.append('\\'); } sb.append(c); } return sb.toString(); }
// Some national prefixes are a substring of others. If extracting the shorter NDD doesn't result // in a number we can format, we try to see if we can extract a longer version here. private boolean ableToExtractLongerNdd() { if (nationalPrefixExtracted.length() > 0) { // Put the extracted NDD back to the national number before attempting to extract a new NDD. nationalNumber.insert(0, nationalPrefixExtracted); // Remove the previously extracted NDD from prefixBeforeNationalNumber. We cannot simply set // it to empty string because people sometimes incorrectly enter national prefix after the // country code, e.g. +44 (0)20-1234-5678. int indexOfPreviousNdd = prefixBeforeNationalNumber.lastIndexOf(nationalPrefixExtracted); prefixBeforeNationalNumber.setLength(indexOfPreviousNdd); } return(!nationalPrefixExtracted.equals(removeNationalPrefixFromNationalNumber())); }
private String findBestMatchingLanguageCode( Set <String> setOfLangs, String language, String script, String region) { StringBuilder fullLocale = constructFullLocale(language, script, region); String fullLocaleStr = fullLocale.toString(); String normalizedLocale = LOCALE_NORMALIZATION_MAP.get(fullLocaleStr); if (normalizedLocale != null) { if (setOfLangs.contains(normalizedLocale)) { return(normalizedLocale); } } if (setOfLangs.contains(fullLocaleStr)) { return(fullLocaleStr); } if (onlyOneOfScriptOrRegionIsEmpty(script, region)) { if (setOfLangs.contains(language)) { return(language); } } else if (script.length() > 0 && region.length() > 0) { StringBuilder langWithScript = new StringBuilder(language).append('_').append(script); String langWithScriptStr = langWithScript.toString(); if (setOfLangs.contains(langWithScriptStr)) { return(langWithScriptStr); } StringBuilder langWithRegion = new StringBuilder(language).append('_').append(region); String langWithRegionStr = langWithRegion.toString(); if (setOfLangs.contains(langWithRegionStr)) { return(langWithRegionStr); } if (setOfLangs.contains(language)) { return(language); } } return(""); }
public static long decodeHexadecimalLong(String value) { long result = 0; var ndigits = 0; for (var i = 2; i < value.length(); i++) { var digit = ParserHelper.scanHexDigit(value[i]); if (ndigits == 0 && digit == 0) { continue; } result <<= 4; result |= digit; if (++ndigits == 17) { throw new NumberFormatException(value); } } return result; }
public static String quoteReplacement(String s) { if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1)) { return(s); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '\\' || c == '$') { sb.append('\\'); } sb.append(c); } return(sb.toString()); }
/** * Returns the current position in the partially formatted phone number of the character which was * previously passed in as the parameter of {@link #inputDigitAndRememberPosition}. */ public int getRememberedPosition() { if (!ableToFormat) { return(originalPosition); } int accruedInputIndex = 0, currentOutputIndex = 0; while (accruedInputIndex < positionToRemember && currentOutputIndex < currentOutput.length()) { if (accruedInputWithoutFormatting.charAt(accruedInputIndex) == currentOutput.charAt(currentOutputIndex)) { accruedInputIndex++; } currentOutputIndex++; } return(currentOutputIndex); }
/** * Attempts to set the formatting template and returns a string which contains the formatted * version of the digits entered so far. */ private String attemptToChooseFormattingPattern() { // We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national // number (excluding national prefix) have been entered. if (nationalNumber.length() >= MIN_LEADING_DIGITS_LENGTH) { getAvailableFormats(nationalNumber.substring(0, MIN_LEADING_DIGITS_LENGTH)); // See if the accrued digits can be formatted properly already. String formattedNumber = attemptToFormatAccruedDigits(); if (formattedNumber.length() > 0) { return(formattedNumber); } return(maybeCreateNewTemplate() ? inputAccruedNationalNumber() : accruedInput.toString()); } else { return(appendNationalNumber(nationalNumber.toString())); } }
private void narrowDownPossibleFormats(String leadingDigits) { int indexOfLeadingDigitsPattern = leadingDigits.length() - MIN_LEADING_DIGITS_LENGTH; Iterator <NumberFormat> it = possibleFormats.iterator(); while (it.hasNext()) { NumberFormat format = it.next(); if (format.leadingDigitsPatternSize() > indexOfLeadingDigitsPattern) { Pattern leadingDigitsPattern = regexCache.getPatternForRegex( format.getLeadingDigitsPattern(indexOfLeadingDigitsPattern)); Matcher m = leadingDigitsPattern.matcher(leadingDigits); if (!m.lookingAt()) { it.remove(); } } // else the particular format has no more specific leadingDigitsPattern, and it should be // retained. } }
private String inputDigitHelper(char nextChar) { Matcher digitMatcher = DIGIT_PATTERN.matcher(formattingTemplate); if (digitMatcher.find(lastMatchPosition)) { String tempTemplate = digitMatcher.replaceFirst(Character.toString(nextChar)); formattingTemplate.replace(0, tempTemplate.length(), tempTemplate); lastMatchPosition = digitMatcher.start(); return(formattingTemplate.substring(0, lastMatchPosition + 1)); } else { if (possibleFormats.size() == 1) { // More digits are entered than we could handle, and there are no other valid patterns to // try. ableToFormat = false; } // else, we just reset the formatting pattern. currentFormattingPattern = ""; return(accruedInput.toString()); } }
// Gets a formatting template which can be used to efficiently format a partial number where // digits are added one by one. private String getFormattingTemplate(String numberPattern, String numberFormat) { // Creates a phone number consisting only of the digit 9 that matches the // numberPattern by applying the pattern to the longestPhoneNumber string. String longestPhoneNumber = "999999999999999"; Matcher m = regexCache.getPatternForRegex(numberPattern).matcher(longestPhoneNumber); m.find(); // this will always succeed String aPhoneNumber = m.group(); // No formatting template can be created if the number of digits entered so far is longer than // the maximum the current formatting rule can accommodate. if (aPhoneNumber.length() < nationalNumber.length()) { return(""); } // Formats the number according to numberFormat String template = aPhoneNumber.replaceAll(numberPattern, numberFormat); // Replaces each digit with character DIGIT_PLACEHOLDER template = template.replaceAll("9", DIGIT_PLACEHOLDER); return(template); }
public static String quote(String s) { int slashEIndex = s.indexOf(new String("\\E")); if (slashEIndex == -1) return new String("\\Q" + s + "\\E"); StringBuilder sb = new StringBuilder(s.length() * 2); sb.append("\\Q"); slashEIndex = 0; int current = 0; while ((slashEIndex = s.indexOf(new String("\\E"), current)) != -1) { sb.append(s.substring(current, slashEIndex)); current = slashEIndex + 2; sb.append("\\E\\\\E\\Q"); } sb.append(s.substring(current, s.length())); sb.append("\\E"); return sb.toString(); }
private String produceEquivalentAlternation(String source) { int len = countChars(source, 0, 1); if (source.length() == len) // source has one character. return source; String @base = source.substring(0,len); String combiningMarks = source.substring(len); String[] perms = producePermutations(combiningMarks); StringBuilder result = new StringBuilder(source); // Add combined permutations for(int x=0; x<perms.Length; x++) { String next = @base + perms[x]; if (x>0) result.append("|"+next); next = composeOneStep(next); if (next != null) result.append("|"+produceEquivalentAlternation(next)); } return result.toString(); }
public StringBuffer(String str) : base(str.length() + 16) { append(str); }
public new /*synchronized*/ int lastIndexOf(String str, int fromIndex) { return(String.lastIndexOf(value, 0, count, str.toCharArray(), 0, str.length(), fromIndex)); }
/* public void writeFloat(float v) { if (pos + 4 <= MAX_BLOCK_SIZE) { Bits.putFloat(buf, pos, v); pos += 4; } else { dout.writeFloat(v); } } public void writeLong(long v) { if (pos + 8 <= MAX_BLOCK_SIZE) { Bits.putLong(buf, pos, v); pos += 8; } else { dout.writeLong(v); } } public void writeDouble(double v) { if (pos + 8 <= MAX_BLOCK_SIZE) { Bits.putDouble(buf, pos, v); pos += 8; } else { dout.writeDouble(v); } } */ public void writeBytes(String s) { int endoff = s.length(); int cpos = 0; int csize = 0; for (int off = 0; off < endoff; ) { if (cpos >= csize) { cpos = 0; csize = Math.min(endoff - off, CHAR_BUF_SIZE); s.getChars(off, off + csize, cbuf, 0); } if (pos >= MAX_BLOCK_SIZE) { drain(); } int n = Math.min(csize - cpos, MAX_BLOCK_SIZE - pos); int stop = pos + n; while (pos < stop) { buf[pos++] = (byte) cbuf[cpos++]; } off += n; } }
private TypeInfo getType(String name) { name = name.trim(); int dimensions = 0; while (name.endsWith("[]")) { dimensions++; name = name.substring(0, name.length() - 2); } TypeInfo result; switch (name) { case "boolean": result = context.TypeSystem.BooleanType; break; case "byte": result = context.TypeSystem.ByteType; break; case "char": result = context.TypeSystem.CharType; break; case "short": result = context.TypeSystem.ShortType; break; case "int": result = context.TypeSystem.IntType; break; case "long": result = context.TypeSystem.LongType; break; case "float": result = context.TypeSystem.FloatType; break; case "double": result = context.TypeSystem.DoubleType; break; default: int idx = name.indexOf("."); String prefix; if (idx == -1) { prefix = name; name = null; } else { prefix = name.substring(0, idx); name = name.substring(idx + 1); } var members = context.MemberResolver.resolveName(context.CurrentType, prefix, Query.empty<TypeInfo>()).toList(); if (!members.any()) { if (name == null) { return null; } var packageName = context.MemberResolver.getPackageFromAlias(prefix); if (packageName == null) { if (context.MemberResolver.TypeFinder.getSubPackages(prefix).any() || context.MemberResolver.TypeFinder.getClasses(prefix).any()) { packageName = prefix; } else { return null; } } var found = false; do { idx = name.indexOf('.'); if (idx == -1) { prefix = name; name = null; } else { prefix = name.substring(0, idx); name = name.substring(idx + 1); } foreach (var s in context.MemberResolver.TypeFinder.getSubPackages(packageName)) { if (s.equals(prefix)) { packageName = packageName + '/' + prefix; found = true; break; } } if (!found && !context.MemberResolver.TypeFinder.getClasses(packageName).contains(prefix)) { return null; } } while (name != null && found); result = context.TypeSystem.getType(packageName + '/' + prefix); } else if (members.count() > 1) { return null; } else { result = members.first().Type; } break; } while (dimensions-- > 0) { type = type.ArrayType; } return result; }
/* void writeFloats(float[] v, int off, int len) { int limit = MAX_BLOCK_SIZE - 4; int endoff = off + len; while (off < endoff) { if (pos <= limit) { int avail = (MAX_BLOCK_SIZE - pos) >> 2; int chunklen = Math.min(endoff - off, avail); floatsToBytes(v, off, buf, pos, chunklen); off += chunklen; pos += chunklen << 2; } else { dout.writeFloat(v[off++]); } } } void writeLongs(long[] v, int off, int len) { int limit = MAX_BLOCK_SIZE - 8; int endoff = off + len; while (off < endoff) { if (pos <= limit) { int avail = (MAX_BLOCK_SIZE - pos) >> 3; int stop = Math.min(endoff, off + avail); while (off < stop) { Bits.putLong(buf, pos, v[off++]); pos += 8; } } else { dout.writeLong(v[off++]); } } } */ /* void writeDoubles(double[] v, int off, int len) { int limit = MAX_BLOCK_SIZE - 8; int endoff = off + len; while (off < endoff) { if (pos <= limit) { int avail = (MAX_BLOCK_SIZE - pos) >> 3; int chunklen = Math.min(endoff - off, avail); doublesToBytes(v, off, buf, pos, chunklen); off += chunklen; pos += chunklen << 3; } else { dout.writeDouble(v[off++]); } } } */ internal long getUTFLength(String s) { int len = s.length(); long utflen = 0; for (int off = 0; off < len; ) { int csize = Math.min(len - off, CHAR_BUF_SIZE); s.getChars(off, off + csize, cbuf, 0); for (int cpos = 0; cpos < csize; cpos++) { char c = cbuf[cpos]; if (c >= 0x0001 && c <= 0x007F) { utflen++; } else if (c > 0x07FF) { utflen += 3; } else { utflen += 2; } } off += csize; } return utflen; }
public void writeChars(String s) { int endoff = s.length(); for (int off = 0; off < endoff; ) { int csize = Math.min(endoff - off, CHAR_BUF_SIZE); s.getChars(off, off + csize, cbuf, 0); writeChars(cbuf, 0, csize); off += csize; } }
internal void writeUTF(String s, long utflen) { if (utflen > 0xFFFFL) { throw new Exception(); } writeShort((int) utflen); if (utflen == (long) s.length()) { writeBytes(s); } else { writeUTFBody(s); } }
private void doTestInContext(String number, String defaultCountry, List<NumberContext> contextPairs, Leniency leniency) { foreach(NumberContext context in contextPairs) { String prefix = context.leadingText; String text = prefix + number + context.trailingText; int start = prefix.length(); int end = start + number.length(); Iterator<PhoneNumberMatch> iterator = phoneUtil.findNumbers(text, defaultCountry, leniency, Long.MAX_VALUE).iterator(); PhoneNumberMatch match = iterator.hasNext() ? iterator.next() : null; assertNotNull("Did not find a number in '" + text + "'; expected '" + number + "'", match); CharSequence extracted = text.subSequence(match.start(), match.end()); assertTrue("Unexpected phone region in '" + text + "'; extracted '" + extracted + "'", start == match.start() && end == match.end()); assertTrue(number.contentEquals(extracted)); assertTrue(match.rawString().contentEquals(extracted)); ensureTermination(text, defaultCountry, leniency); } }
public virtual int lastIndexOf(String str, int fromIndex) { return(String.lastIndexOf(value, 0, count, str.toCharArray(), 0, str.length(), fromIndex)); }
public static bool isNullOrEmpty(String str) { return str == null || str.length() == 0; }
private void narrowDownPossibleFormats(String leadingDigits) { int indexOfLeadingDigitsPattern = leadingDigits.length() - MIN_LEADING_DIGITS_LENGTH; Iterator<NumberFormat> it = possibleFormats.iterator(); while (it.hasNext()) { NumberFormat format = it.next(); if (format.leadingDigitsPatternSize() > indexOfLeadingDigitsPattern) { Pattern leadingDigitsPattern = regexCache.getPatternForRegex( format.getLeadingDigitsPattern(indexOfLeadingDigitsPattern)); Matcher m = leadingDigitsPattern.matcher(leadingDigits); if (!m.lookingAt()) { it.remove(); } } // else the particular format has no more specific leadingDigitsPattern, and it should be // retained. } }
public void writeChars(String s) { int len = s.length(); for (int i = 0 ; i < len ; i++) { int v = s.charAt(i); @out.write((int)(((uint)v) >> 8) & 0xFF); @out.write((int)(((uint)v) >> 0) & 0xFF); } incCount(len * 2); }
public Matcher appendReplacement(StringBuffer sb, String replacement) { // If no match, return error if (first < 0) { throw new InvalidOperationException("No match available"); } // Process substitution string to replace group references with groups int cursor = 0; StringBuilder result = new StringBuilder(); while (cursor < replacement.length()) { char nextChar = replacement.charAt(cursor); if (nextChar == '\\') { cursor++; nextChar = replacement.charAt(cursor); result.append(nextChar); cursor++; } else if (nextChar == '$') { // Skip past $ cursor++; // A StringIndexOutOfBoundsException is thrown if // this "$" is the last character in replacement // string in current implementation, a IAE might be // more appropriate. nextChar = replacement.charAt(cursor); int refNum = -1; if (nextChar == '{') { cursor++; StringBuilder gsb = new StringBuilder(); while (cursor < replacement.length()) { nextChar = replacement.charAt(cursor); if (ASCII.isLower(nextChar) || ASCII.isUpper(nextChar) || ASCII.isDigit(nextChar)) { gsb.append(nextChar); cursor++; } else { break; } } if (gsb.length() == 0) { throw new IllegalArgumentException( "named capturing group has 0 length name"); } if (nextChar != '}') { throw new IllegalArgumentException( "named capturing group is missing trailing '}'"); } String gname = gsb.toString(); if (ASCII.isDigit(gname.charAt(0))) { throw new IllegalArgumentException( "capturing group name {" + gname + "} starts with digit character"); } if (!parentPattern.namedGroups().containsKey(gname)) { throw new IllegalArgumentException( "No group with name {" + gname + "}"); } refNum = parentPattern.namedGroups().get(gname); cursor++; } else { // The first number is always a group refNum = (int)nextChar - '0'; if ((refNum < 0) || (refNum > 9)) { throw new IllegalArgumentException( "Illegal group reference"); } cursor++; // Capture the largest legal group string boolean done = false; while (!done) { if (cursor >= replacement.length()) { break; } int nextDigit = replacement.charAt(cursor) - '0'; if ((nextDigit < 0) || (nextDigit > 9)) // not a number { break; } int newRefNum = (refNum * 10) + nextDigit; if (groupCount() < newRefNum) { done = true; } else { refNum = newRefNum; cursor++; } } } // Append group if (start(refNum) != -1 && end(refNum) != -1) { result.append(text, start(refNum), end(refNum)); } } else { result.append(nextChar); cursor++; } } // Append the intervening text sb.append(text, lastAppendPosition, first); // Append the match substitution sb.append(result); lastAppendPosition = last; return(this); }
/** Returns the exclusive end index of the matched phone number within the searched text. */ public int end() { return(_start + _rawString.length()); }
private PreprocessorLexicalUnit scanKeyword(String suffix, PreprocessorLexicalUnit keyword) { bool isKeyword = true; for (int i = 0; i < suffix.length(); i++) { char c = suffix[i]; if (this.Next == -1 || (char)this.Next != c) { isKeyword = false; break; } advance(); } if (this.Next != -1 && ParserHelper.isIdentifierPartChar(this.Next)) { scanIdentifierPart(); return PreprocessorLexicalUnit.Symbol; } return (isKeyword) ? keyword : PreprocessorLexicalUnit.Symbol; }
private void replaceCref(Element element, bool exception, Iterable<MemberInfo> members, String suffix, String arguments) { if (members.count() > 1 && !members.all(p => p.MemberKind == MemberKind.Method)) { context.addWarning(CompileErrorId.UnresolvedCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } var member = members.first(); switch (member.MemberKind) { case Type: replaceCref(element, exception, member.Type, suffix, arguments); break; case Field: if (exception) { context.addWarning(CompileErrorId.ExpectedExceptionInCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } if (suffix != null || arguments != null) { context.addWarning(CompileErrorId.UnresolvedCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } element.setAttribute("cref", getIdString(member.Field)); break; case Property: if (exception) { context.addWarning(CompileErrorId.ExpectedExceptionInCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } if (suffix != null || arguments != null) { context.addWarning(CompileErrorId.UnresolvedCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); return; } element.setAttribute("cref", getIdString(member.GetAccessor ?? member.SetAccessor)); break; case Method: if (!exception && suffix == null) { if (arguments == null && members.count() == 1) { element.setAttribute("cref", getIdString(member.Method)); return; } else if (arguments != null && arguments.endsWith(")")) { var args = new ArrayList<TypeInfo>(); if (arguments.length() > 2) { arguments = arguments.substring(1, arguments.length() - 1); int idx; while ((idx = arguments.indexOf(',')) != -1) { var name = arguments.substring(0, idx); arguments = arguments.substring(idx + 1); var type = getType(name); if (type == null) { goto failed; } args.add(type); } if (arguments.length() == 0) { goto failed; } var type = getType(arguments); if (type == null) { goto failed; } args.add(type); } foreach (var m in members) { if (m.Method.Parameters.select(p => p.Type).sequenceEqual(args)) { element.setAttribute("cref", getIdString(m.Method)); return; } } } } failed: context.addWarning(CompileErrorId.UnresolvedCref, node, element.getAttribute("cref")); element.setAttribute("cref", "!" + element.getAttribute("cref")); break; default: break; } }
private void normalize() { boolean inCharClass = false; int lastCodePoint = -1; // Convert pattern into normalizedD form normalizedPattern = Normalizer.normalize(pattern, Normalizer.Form.NFD); patternLength = normalizedPattern.length(); // Modify pattern to match canonical equivalences StringBuilder newPattern = new StringBuilder(patternLength); for(int i=0; i<patternLength; ) { int c = normalizedPattern.codePointAt(i); StringBuilder sequenceBuffer; if ((Character.getType(c) == Character.NON_SPACING_MARK) && (lastCodePoint != -1)) { sequenceBuffer = new StringBuilder(); sequenceBuffer.appendCodePoint(lastCodePoint); sequenceBuffer.appendCodePoint(c); while(Character.getType(c) == Character.NON_SPACING_MARK) { i += Character.charCount(c); if (i >= patternLength) break; c = normalizedPattern.codePointAt(i); sequenceBuffer.appendCodePoint(c); } String ea = produceEquivalentAlternation( sequenceBuffer.toString()); newPattern.setLength(newPattern.length()-Character.charCount(lastCodePoint)); newPattern.append("(?:").append(ea).append(")"); } else if (c == '[' && lastCodePoint != '\\') { i = normalizeCharClass(newPattern, i); } else { newPattern.appendCodePoint(c); } lastCodePoint = c; i += Character.charCount(c); } normalizedPattern = newPattern.toString(); }
public void StaticString() { String s1 = env.NewString("test"); Assert.AreEqual(4, s1.length()); }
private boolean onlyOneOfScriptOrRegionIsEmpty(String script, String region) { return((script.length() == 0 && region.length() > 0) || (region.length() == 0 && script.length() > 0)); }
/** * Gets the name of the file that contains the mapping data for the {@code countryCallingCode} in * the language specified. * * @param countryCallingCode the country calling code of phone numbers which the data file * contains * @param language two-letter lowercase ISO language codes as defined by ISO 639-1 * @param script four-letter titlecase (the first letter is uppercase and the rest of the letters * are lowercase) ISO script codes as defined in ISO 15924 * @param region two-letter uppercase ISO country codes as defined by ISO 3166-1 * @return the name of the file, or empty string if no such file can be found */ internal String getFileName(int countryCallingCode, String language, String script, String region) { if (language.length() == 0) { return ""; } int index = Arrays.binarySearch(countryCallingCodes, countryCallingCode); if (index < 0) { return ""; } Set<String> setOfLangs = availableLanguages.get(index); if (setOfLangs.size() > 0) { String languageCode = findBestMatchingLanguageCode(setOfLangs, language, script, region); if (languageCode.length() > 0) { StringBuilder fileName = new StringBuilder(); fileName.append(countryCallingCode).append('_').append(languageCode); return fileName.toString(); } } return ""; }
private String findBestMatchingLanguageCode( Set<String> setOfLangs, String language, String script, String region) { StringBuilder fullLocale = constructFullLocale(language, script, region); String fullLocaleStr = fullLocale.toString(); String normalizedLocale = LOCALE_NORMALIZATION_MAP.get(fullLocaleStr); if (normalizedLocale != null) { if (setOfLangs.contains(normalizedLocale)) { return normalizedLocale; } } if (setOfLangs.contains(fullLocaleStr)) { return fullLocaleStr; } if (onlyOneOfScriptOrRegionIsEmpty(script, region)) { if (setOfLangs.contains(language)) { return language; } } else if (script.length() > 0 && region.length() > 0) { StringBuilder langWithScript = new StringBuilder(language).append('_').append(script); String langWithScriptStr = langWithScript.toString(); if (setOfLangs.contains(langWithScriptStr)) { return langWithScriptStr; } StringBuilder langWithRegion = new StringBuilder(language).append('_').append(region); String langWithRegionStr = langWithRegion.toString(); if (setOfLangs.contains(langWithRegionStr)) { return langWithRegionStr; } if (setOfLangs.contains(language)) { return language; } } return ""; }
private String inputDigitWithOptionToRememberPosition(char nextChar, boolean rememberPosition) { accruedInput.append(nextChar); if (rememberPosition) { originalPosition = accruedInput.length(); } // We do formatting on-the-fly only when each character entered is either a digit, or a plus // sign (accepted at the start of the number only). if (!isDigitOrLeadingPlusSign(nextChar)) { ableToFormat = false; inputHasFormatting = true; } else { nextChar = normalizeAndAccrueDigitsAndPlusSign(nextChar, rememberPosition); } if (!ableToFormat) { // When we are unable to format because of reasons other than that formatting chars have been // entered, it can be due to really long IDDs or NDDs. If that is the case, we might be able // to do formatting again after extracting them. if (inputHasFormatting) { return(accruedInput.toString()); } else if (attemptToExtractIdd()) { if (attemptToExtractCountryCallingCode()) { return(attemptToChoosePatternWithPrefixExtracted()); } } else if (ableToExtractLongerNdd()) { // Add an additional space to separate long NDD and national significant number for // readability. We don't set shouldAddSpaceAfterNationalPrefix to true, since we don't want // this to change later when we choose formatting templates. prefixBeforeNationalNumber.append(SEPARATOR_BEFORE_NATIONAL_NUMBER); return(attemptToChoosePatternWithPrefixExtracted()); } return(accruedInput.toString()); } // We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits (the plus // sign is counted as a digit as well for this purpose) have been entered. switch (accruedInputWithoutFormatting.length()) { case 0: case 1: case 2: return(accruedInput.toString()); default: if (accruedInputWithoutFormatting.length() == 3) { if (attemptToExtractIdd()) { isExpectingCountryCallingCode = true; } else // No IDD or plus sign is found, might be entering in national format. { nationalPrefixExtracted = removeNationalPrefixFromNationalNumber(); return(attemptToChooseFormattingPattern()); } } if (isExpectingCountryCallingCode) { if (attemptToExtractCountryCallingCode()) { isExpectingCountryCallingCode = false; } return(prefixBeforeNationalNumber + nationalNumber.toString()); } if (possibleFormats.size() > 0) // The formatting pattern is already chosen. { String tempNationalNumber = inputDigitHelper(nextChar); // See if the accrued digits can be formatted properly already. If not, use the results // from inputDigitHelper, which does formatting based on the formatting pattern chosen. String formattedNumber = attemptToFormatAccruedDigits(); if (formattedNumber.length() > 0) { return(formattedNumber); } narrowDownPossibleFormats(nationalNumber.toString()); if (maybeCreateNewTemplate()) { return(inputAccruedNationalNumber()); } return(ableToFormat ? appendNationalNumber(tempNationalNumber) : accruedInput.toString()); } else { return(attemptToChooseFormattingPattern()); } } }
static int writeUTF(String str, DataOutputStream @out) { int strlen = str.length(); int utflen = 0; int c, count = 0; /* use charAt instead of copying String to char array */ int i; for (i = 0; i < strlen; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { utflen++; } else if (c > 0x07FF) { utflen += 3; } else { utflen += 2; } } if (utflen > 65535) throw new Exception( "encoded string too long: " + utflen + " bytes"); byte[] bytearr = null; if (@out is DataOutputStream) { DataOutputStream dos = (DataOutputStream)@out; if(dos.bytearr == null || (dos.bytearr.Length < (utflen+2))) dos.bytearr = new byte[(utflen*2) + 2]; bytearr = dos.bytearr; } else { bytearr = new byte[utflen+2]; } bytearr[count++] = (byte) ((int)(((uint)utflen) >> 8) & 0xFF); bytearr[count++] = (byte) ((int)(((uint)utflen) >> 0) & 0xFF); i=0; for (i=0; i<strlen; i++) { c = str.charAt(i); if (!((c >= 0x0001) && (c <= 0x007F))) break; bytearr[count++] = (byte) c; } for (;i < strlen; i++){ c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { bytearr[count++] = (byte) c; } else if (c > 0x07FF) { bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F)); bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); } else { bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); } } @out.write(bytearr, 0, utflen+2); return utflen + 2; }
private String[] producePermutations(String input) { if (input.length() == countChars(input, 0, 1)) return new String[] {input}; if (input.length() == countChars(input, 0, 2)) { int c0 = Character.codePointAt(input, 0); int c1 = Character.codePointAt(input, Character.charCount(c0)); if (getClass(c1) == getClass(c0)) { return new String[] {input}; } String[] result = new String[2]; result[0] = input; StringBuilder sb = new StringBuilder(2); sb.appendCodePoint(c1); sb.appendCodePoint(c0); result[1] = sb.toString(); return result; } int length = 1; int nCodePoints = countCodePoints(input); for(int x=1; x<nCodePoints; x++) length = length * (x+1); String[] temp = new String[length]; int[] combClass = new int[nCodePoints]; for(int x=0, i=0; x<nCodePoints; x++) { int c = Character.codePointAt(input, i); combClass[x] = getClass(c); i += Character.charCount(c); } // For each char, take it out and add the permutations // of the remaining chars int index = 0; int len; // offset maintains the index in code units. for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) { continue1: len = countChars(input, offset, 1); boolean skip = false; for(int y=x-1; y>=0; y--) { if (combClass[y] == combClass[x]) { offset+=len; if (x < nCodePoints) goto continue1; goto end1; } } StringBuilder sb = new StringBuilder(input); String otherChars = sb.delete(offset, offset+len).toString(); String[] subResult = producePermutations(otherChars); String prefix = input.substring(offset, offset+len); for(int y=0; y<subResult.Length; y++) temp[index++] = prefix + subResult[y]; } end1: String[] _result = new String[index]; for (int x=0; x<index; x++) _result[x] = temp[x]; return _result; }
private boolean onlyOneOfScriptOrRegionIsEmpty(String script, String region) { return (script.length() == 0 && region.length() > 0) || (region.length() == 0 && script.length() > 0); }
/* void writeLongUTF(String s) { writeLongUTF(s, getUTFLength(s)); } internal void writeLongUTF(String s, long utflen) { writeLong(utflen); if (utflen == (long) s.length()) { writeBytes(s); } else { writeUTFBody(s); } } */ private void writeUTFBody(String s) { int limit = MAX_BLOCK_SIZE - 3; int len = s.length(); for (int off = 0; off < len; ) { int csize = Math.min(len - off, CHAR_BUF_SIZE); s.getChars(off, off + csize, cbuf, 0); for (int cpos = 0; cpos < csize; cpos++) { char c = cbuf[cpos]; if (pos <= limit) { if (c <= 0x007F && c != 0) { buf[pos++] = (byte) c; } else if (c > 0x07FF) { buf[pos + 2] = (byte) (0x80 | ((c >> 0) & 0x3F)); buf[pos + 1] = (byte) (0x80 | ((c >> 6) & 0x3F)); buf[pos + 0] = (byte) (0xE0 | ((c >> 12) & 0x0F)); pos += 3; } else { buf[pos + 1] = (byte) (0x80 | ((c >> 0) & 0x3F)); buf[pos + 0] = (byte) (0xC0 | ((c >> 6) & 0x1F)); pos += 2; } } else { // write one byte at a time to normalize block if (c <= 0x007F && c != 0) { write(c); } else if (c > 0x07FF) { write(0xE0 | ((c >> 12) & 0x0F)); write(0x80 | ((c >> 6) & 0x3F)); write(0x80 | ((c >> 0) & 0x3F)); } else { write(0xC0 | ((c >> 6) & 0x1F)); write(0x80 | ((c >> 0) & 0x3F)); } } } off += csize; } }
/** * Exhaustively searches for phone numbers from each index within {@code text} to test that * finding matches always terminates. */ private void ensureTermination(String text, String defaultCountry, Leniency leniency) { for (int index = 0; index <= text.length(); index++) { String sub = text.substring(index); StringBuilder matches = new StringBuilder(); // Iterates over all matches. foreach(PhoneNumberMatch match in phoneUtil.findNumbers(sub, defaultCountry, leniency, Long.MAX_VALUE)) { matches.append(", ").append(match.toString()); } } }
/* private void readObject(java.io.ObjectInputStream s) { // Read in all fields s.defaultReadObject(); // Initialize counts capturingGroupCount = 1; localCount = 0; // if length > 0, the Pattern is lazily compiled compiled = false; if (pattern.length() == 0) { root = new Start(lastAccept); matchRoot = lastAccept; compiled = true; } } */ private Pattern(String p, int f) { _pattern = p; _flags = f; // to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present if ((_flags & UNICODE_CHARACTER_CLASS) != 0) _flags |= UNICODE_CASE; // Reset group index count capturingGroupCount = 1; localCount = 0; if (_pattern.length() > 0) { compile(); } else { root = new Start(lastAccept); matchRoot = lastAccept; } }
static int writeUTF(String str, DataOutputStream @out) { int strlen = str.length(); int utflen = 0; int c, count = 0; /* use charAt instead of copying String to char array */ int i; for (i = 0; i < strlen; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { utflen++; } else if (c > 0x07FF) { utflen += 3; } else { utflen += 2; } } if (utflen > 65535) { throw new Exception( "encoded string too long: " + utflen + " bytes"); } byte[] bytearr = null; if (@out is DataOutputStream) { DataOutputStream dos = (DataOutputStream)@out; if (dos.bytearr == null || (dos.bytearr.Length < (utflen + 2))) { dos.bytearr = new byte[(utflen * 2) + 2]; } bytearr = dos.bytearr; } else { bytearr = new byte[utflen + 2]; } bytearr[count++] = (byte)((int)(((uint)utflen) >> 8) & 0xFF); bytearr[count++] = (byte)((int)(((uint)utflen) >> 0) & 0xFF); i = 0; for (i = 0; i < strlen; i++) { c = str.charAt(i); if (!((c >= 0x0001) && (c <= 0x007F))) { break; } bytearr[count++] = (byte)c; } for (; i < strlen; i++) { c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { bytearr[count++] = (byte)c; } else if (c > 0x07FF) { bytearr[count++] = (byte)(0xE0 | ((c >> 12) & 0x0F)); bytearr[count++] = (byte)(0x80 | ((c >> 6) & 0x3F)); bytearr[count++] = (byte)(0x80 | ((c >> 0) & 0x3F)); } else { bytearr[count++] = (byte)(0xC0 | ((c >> 6) & 0x1F)); bytearr[count++] = (byte)(0x80 | ((c >> 0) & 0x3F)); } } @out.write(bytearr, 0, utflen + 2); return(utflen + 2); }
public static bool hasExtension(String path) { int index = path.lastIndexOf('.'); if (index == -1) { return false; } return (index + 1) != path.length(); }
public static long parseLong(String s, int radix) { if (s == null) { throw new NumberFormatException("null"); } if (radix < Character.MIN_RADIX) { throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX"); } if (radix > Character.MAX_RADIX) { throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX"); } long result = 0; boolean negative = false; int i = 0, len = s.length(); long limit = -Long.MAX_VALUE; long multmin; int digit; if (len > 0) { char firstChar = s.charAt(0); if (firstChar < '0') // Possible leading "+" or "-" { if (firstChar == '-') { negative = true; limit = Long.MIN_VALUE; } else if (firstChar != '+') { throw NumberFormatException.forInputString(s); } if (len == 1) // Cannot have lone "+" or "-" { throw NumberFormatException.forInputString(s); } i++; } multmin = limit / radix; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE digit = Character.digit(s.charAt(i++), radix); if (digit < 0) { throw NumberFormatException.forInputString(s); } if (result < multmin) { throw NumberFormatException.forInputString(s); } result *= radix; if (result < limit + digit) { throw NumberFormatException.forInputString(s); } result -= digit; } } else { throw NumberFormatException.forInputString(s); } return(negative ? result : -result); }
public static String combine(String path1, String path2) { if (path1 == null) { throw new NullPointerException("path1"); } if (path2 == null) { throw new NullPointerException("path2"); } if (path1.length() == 0) { return path2; } if (path2.length() == 0) { return path1; } if (path2.length() > 2 && path2[1] == VOLUME_SEPARATOR_CHAR) { return path2; } var path1LastChar = path1[path1.length() - 1]; var path2LastChar = path2[0]; if (path1LastChar == DIRECTORY_SEPARATOR_CHAR || path1LastChar == ALT_DIRECTORY_SEPARATOR_CHAR || path1LastChar == VOLUME_SEPARATOR_CHAR || path2LastChar == DIRECTORY_SEPARATOR_CHAR || path2LastChar == ALT_DIRECTORY_SEPARATOR_CHAR) { return path1 + path2; } else { return path1 + DIRECTORY_SEPARATOR_CHAR + path2; } }
public Matcher appendReplacement(StringBuffer sb, String replacement) { // If no match, return error if (first < 0) throw new InvalidOperationException("No match available"); // Process substitution string to replace group references with groups int cursor = 0; StringBuilder result = new StringBuilder(); while (cursor < replacement.length()) { char nextChar = replacement.charAt(cursor); if (nextChar == '\\') { cursor++; nextChar = replacement.charAt(cursor); result.append(nextChar); cursor++; } else if (nextChar == '$') { // Skip past $ cursor++; // A StringIndexOutOfBoundsException is thrown if // this "$" is the last character in replacement // string in current implementation, a IAE might be // more appropriate. nextChar = replacement.charAt(cursor); int refNum = -1; if (nextChar == '{') { cursor++; StringBuilder gsb = new StringBuilder(); while (cursor < replacement.length()) { nextChar = replacement.charAt(cursor); if (ASCII.isLower(nextChar) || ASCII.isUpper(nextChar) || ASCII.isDigit(nextChar)) { gsb.append(nextChar); cursor++; } else { break; } } if (gsb.length() == 0) throw new IllegalArgumentException( "named capturing group has 0 length name"); if (nextChar != '}') throw new IllegalArgumentException( "named capturing group is missing trailing '}'"); String gname = gsb.toString(); if (ASCII.isDigit(gname.charAt(0))) throw new IllegalArgumentException( "capturing group name {" + gname + "} starts with digit character"); if (!parentPattern.namedGroups().containsKey(gname)) throw new IllegalArgumentException( "No group with name {" + gname + "}"); refNum = parentPattern.namedGroups().get(gname); cursor++; } else { // The first number is always a group refNum = (int)nextChar - '0'; if ((refNum < 0)||(refNum > 9)) throw new IllegalArgumentException( "Illegal group reference"); cursor++; // Capture the largest legal group string boolean done = false; while (!done) { if (cursor >= replacement.length()) { break; } int nextDigit = replacement.charAt(cursor) - '0'; if ((nextDigit < 0)||(nextDigit > 9)) { // not a number break; } int newRefNum = (refNum * 10) + nextDigit; if (groupCount() < newRefNum) { done = true; } else { refNum = newRefNum; cursor++; } } } // Append group if (start(refNum) != -1 && end(refNum) != -1) result.append(text, start(refNum), end(refNum)); } else { result.append(nextChar); cursor++; } } // Append the intervening text sb.append(text, lastAppendPosition, first); // Append the match substitution sb.append(result); lastAppendPosition = last; return this; }
public new int indexOf(String str, int fromIndex) { return(String.indexOf(value, 0, count, str.toCharArray(), 0, str.length(), fromIndex)); }