Java Code Examples for java.util.regex.Matcher#hitEnd()

The following examples show how to use java.util.regex.Matcher#hitEnd() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Transformations.java    From AliceBot with Apache License 2.0 6 votes vote down vote up
/**
 * Turns the entry to UPPERCASE, takes sequences of non-alphanumeric
 * characters out of it (replacing them with a single whitespace) and sees
 * that the entry is trimmed off leading and trailing whitespaces.
 */
private String fit(String input, Mapper mapper) {

	input = input.toUpperCase();

	Matcher matcher = fitting.matcher(input);
	StringBuffer buffer = new StringBuffer();
	while (!matcher.hitEnd() && matcher.find()) {
		mapper.prepare(input, matcher.group(), " ");
		mapper.update(matcher.start());
		matcher.appendReplacement(buffer, " ");
	}

	matcher.appendTail(buffer);
	return buffer.toString();
}
 
Example 2
Source File: Transformations.java    From AliceBot with Apache License 2.0 6 votes vote down vote up
private String substitute(String input, Mapper mapper) {
	StringBuffer buffer = new StringBuffer();
	for (String find : correction.keySet()) {
		Pattern pattern = Pattern.compile(find, CASE_INSENSITIVE
				| UNICODE_CASE);
		Matcher matcher = pattern.matcher(input);
		String replace = correction.get(find);

		mapper.prepare(input, find, replace);
		while (!matcher.hitEnd() && matcher.find()) {
			mapper.update(matcher.start() + 1);
			matcher.appendReplacement(buffer, replace);
		}

		matcher.appendTail(buffer);
		input = buffer.toString();
		buffer.delete(0, buffer.length());
	}

	return input;
}
 
Example 3
Source File: EntityPropertyClassNameResolver.java    From doma-gen with Apache License 2.0 6 votes vote down vote up
/**
 * エンティティプロパティのクラス名を解決します。
 *
 * @param entityDesc エンティティ記述
 * @param propertyName エンティティプロパティ名
 * @param defaultPropertyClassName エンティティプロパティのデフォルトのクラス名
 * @return エンティティプロパティのクラス名
 */
public String resolve(
    EntityDesc entityDesc, String propertyName, String defaultPropertyClassName) {
  String qualifiedPropertyName = entityDesc.getQualifiedName() + "@" + propertyName;
  for (Map.Entry<Pattern, String> entry : patternMap.entrySet()) {
    Pattern pattern = entry.getKey();
    String input = pattern.pattern().contains("@") ? qualifiedPropertyName : propertyName;
    Matcher matcher = pattern.matcher(input);
    if (!matcher.matches()) {
      continue;
    }
    matcher.reset();
    StringBuffer buf = new StringBuffer();
    String replacement = entry.getValue();
    for (; matcher.find(); ) {
      matcher.appendReplacement(buf, replacement);
      if (matcher.hitEnd()) {
        break;
      }
    }
    matcher.appendTail(buf);
    return buf.toString();
  }
  return defaultPropertyClassName;
}
 
Example 4
Source File: Transformations.java    From AliceBot with Apache License 2.0 6 votes vote down vote up
private String substitute(String input, Mapper mapper) {
    StringBuffer buffer = new StringBuffer();
    for (String find : correction.keySet()) {
        Pattern pattern = Pattern.compile(find, CASE_INSENSITIVE | UNICODE_CASE);
        Matcher matcher = pattern.matcher(input);
        String replace = correction.get(find);

        mapper.prepare(input, find, replace);
        while (!matcher.hitEnd() && matcher.find()) {
            mapper.update(matcher.start() + 1);
            matcher.appendReplacement(buffer, replace);
        }

        matcher.appendTail(buffer);
        input = buffer.toString();
        buffer.delete(0, buffer.length());
    }

    return input;
}
 
Example 5
Source File: JsEmbeddingProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Collection<Embedding> createEmbedding(Snapshot snapshot, int offset, int len) {
    Collection<Embedding> es = new ArrayList<>();
    CharSequence text = snapshot.getText().subSequence(offset, offset + len);
    Matcher matcher = GENERIC_MARK_PATTERN.matcher(text);
    int tmpOffset = 0;
    while(matcher.find()) {
        int start = matcher.start();
        int end = matcher.end();
        if(start != end) {
            //create embedding from the original
            es.add(snapshot.create(offset + tmpOffset, start - tmpOffset, JS_MIMETYPE));
            tmpOffset = end;
            if(!matcher.hitEnd()) {
                //follows the delimiter - @@@ - convert it to the GENERATED_JS_IDENTIFIER
                es.add(snapshot.create(GENERATED_JS_IDENTIFIER, JS_MIMETYPE));
            }
        }
    }
    es.add(snapshot.create(offset + tmpOffset, text.length() - tmpOffset, JS_MIMETYPE));
    return es;
}
 
Example 6
Source File: PreferParser.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
private static Map<String, String> parseParameters(final String parameters) {
  Map<String, String> result = new HashMap<>();
  String separator = "";
  int start = 0;
  Matcher matcher = PARAMETER.matcher(parameters.trim());
  while (matcher.find() && matcher.start() == start) {
    start = matcher.end();
    if (matcher.group(1) != null) {
      separator = matcher.group(1);
    } else if (separator != null) {
      final String name = matcher.group(2).toLowerCase(Locale.ROOT);
      // We have to keep already existing parameters.
      if (!result.containsKey(name)) {
        result.put(name, getValue(matcher.group(3)));
      }
      separator = null;
    } else {
      return null;
    }
  }
  return matcher.hitEnd() ? Collections.unmodifiableMap(result) : null;
}
 
Example 7
Source File: PreferParser.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private static void parse(final String value, final Map<String, Preference> result) {
  Map<String, Preference> partResult = new HashMap<>();
  String separator = "";
  int start = 0;
  Matcher matcher = PREFERENCE.matcher(value.trim());
  while (matcher.find() && matcher.start() == start) {
    start = matcher.end();
    if (matcher.group(1) != null) {
      separator = matcher.group(1);
    } else if (separator != null) {
      final String name = matcher.group(2).toLowerCase(Locale.ROOT);
      // RFC 7240:
      // If any preference is specified more than once, only the first instance is to be
      // considered. All subsequent occurrences SHOULD be ignored without signaling
      // an error or otherwise altering the processing of the request.
      if (!partResult.containsKey(name)) {
        final String preferenceValue = getValue(matcher.group(3));
        final Map<String, String> parameters =
            matcher.group(4) == null || matcher.group(4).isEmpty() ? null :
              parseParameters(matcher.group(4));
        partResult.put(name, new Preference(preferenceValue, parameters));
      }
      separator = null;
    } else {
      return;
    }
  }
  if (matcher.hitEnd()) {
    // Here we also have to keep already existing preferences.
    for (final Map.Entry<String, Preference> entry : partResult.entrySet()) {
      if (!result.containsKey(entry.getKey())) {
        result.put(entry.getKey(), entry.getValue());
      }
    }
  }
}
 
Example 8
Source File: MatcherTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void hitEndTest(boolean callFind, String testNo, String regex,
        String input, boolean hit) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    if (callFind) {
        matcher.find();
    } else {
        matcher.matches();
    }
    boolean h = matcher.hitEnd();

    assertTrue(testNo, h == hit);
}
 
Example 9
Source File: AdvancedFilterValidator.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/** Checks if the regex would at least have the chance to match if the matching path starts with root path.
 * 
 * @param regex
 * @param rootPath
 * @return */
static boolean isRegexValidForRootPath(String regex, String rootPath) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(rootPath);
    if (matcher.matches()) {
        return true;
    }
    return matcher.hitEnd();
}
 
Example 10
Source File: StringFormatUtils.java    From datakernel with Apache License 2.0 5 votes vote down vote up
/**
 * Parses value to Period.
 * 1 year 2 months 3 days == Period.of(1, 2, 3)
 * Every value can be negative, but you can't make all Period negative by negating year.
 * In ISO format you can write -P1Y2M, which means -1 years -2 months in this format
 * There can't be any spaces between '-' and DIGIT:
 * -1  - Right
 * - 2 - Wrong
 */
public static Period parsePeriod(String string) {
	string = string.trim();
	if (string.startsWith("-P") || string.startsWith("P")) {
		return Period.parse(string);
	}
	int years = 0, months = 0, days = 0;
	Set<String> units = new HashSet<>();

	Matcher matcher = PERIOD_PATTERN.matcher(string.trim().toLowerCase());
	int lastEnd = 0;
	while (!matcher.hitEnd()) {
		if (!matcher.find() || matcher.start() != lastEnd) {
			throw new IllegalArgumentException("Invalid period: " + string);
		}
		lastEnd = matcher.end();
		String unit = matcher.group("unit");
		if (!unit.endsWith("s")) {
			unit += "s";
		}
		if (!units.add(unit)) {
			throw new IllegalArgumentException("Time unit: " + unit + " occurs more than once.");
		}
		int result = Integer.parseInt(matcher.group("time"));
		switch (unit) {
			case "years":
				years = result;
				break;
			case "months":
				months = result;
				break;
			case "days":
				days = result;
				break;
		}
	}
	return Period.of(years, months, days);
}
 
Example 11
Source File: XCldrStub.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
public static int findMismatch(Matcher m, CharSequence s) {
    int i;
    for (i = 1; i < s.length(); ++i) {
        boolean matches = m.reset(s.subSequence(0, i)).matches();
        if (!matches && !m.hitEnd()) {
            break;
        }
    }
    return i - 1;
}
 
Example 12
Source File: CsvPrinter.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Helper function to replace line breaks in a string with a custom value
 * before printing.
 * <p>
 * This method may be used by inheriting classes, if the particular format
 * does not support line breaks.
 *
 * @param value     value to replace
 * @param lineBreak value, that is used for replacement of line breaks - if null, &lt;br/&gt;
 *                  is used
 * @return value with replaced line breaks
 */
protected static String replaceLineBreaks(String value, String lineBreak) {
    value = StringUtils.trimToNull(value);
    if (value == null) return null;
    if (lineBreak == null) lineBreak = "<br/>";
    Matcher m = LINES.matcher(value);
    StringBuilder out = new StringBuilder();
    while (m.find()) {
        out.append(StringUtils.trimToEmpty(m.group()));
        if (!m.hitEnd()) out.append(lineBreak);
    }
    return out.toString();
}
 
Example 13
Source File: Strings.java    From HolandaCatalinaFw with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the place where the regex is no matching with the value.
 * @param matcher Matcher instance.
 * @param value Value to found.
 * @return Returns the index into the value where the regex is not matching.
 */
public static final int getNoMatchPlace(Matcher matcher, String value) {
    int result = 0;
    for (int i = value.length(); i > 0; --i) {
        Matcher region = matcher.region(0, i);
        if (region.matches() || region.hitEnd()) {
            result = i;
            break;
        }
    }
    return result;
}
 
Example 14
Source File: FancyChat.java    From ForgeHax with MIT License 5 votes vote down vote up
private String makeLeet(String message) {
  char[] messageArray;
  
  message = message.replaceAll("(?i)dude", "d00d").replaceAll("(^|\\s)ph", "$1f");
  
  messageArray = message.toCharArray();
  // match and replace the last only S in a word
  Matcher zMatcher = Pattern.compile("(?<![sS])([sS])(?:[^\\w]|$)").matcher(message);
  
  while (!zMatcher.hitEnd()) {
    if (zMatcher.find()) {
      if (zMatcher.group(1).equals("s")) {
        messageArray[zMatcher.end(1) - 1] = 'z';
      } else {
        messageArray[zMatcher.end(1) - 1] = 'Z';
      }
    }
  }
  
  StringBuilder builder = new StringBuilder();
  Random random = new Random();
  for (char c : messageArray) {
    int key = Character.toUpperCase(c);
    // half the probability for LEET
    if (random.nextInt(2) == 0
        && LeetMap.get(key) != null
        && (LeetProbability.get(key) == null
        || LeetProbability.get(key) > random.nextInt(100))) {
      builder.append(LeetMap.get(key));
    } else {
      builder.append(c);
    }
  }
  
  return builder.toString();
}
 
Example 15
Source File: Transformations.java    From AliceBot with Apache License 2.0 5 votes vote down vote up
/**
 * 开启大写,
 * Turns the entry to UPPERCASE, takes sequences of non-alphanumeric characters out of it (replacing them with a single whitespace) and sees that the entry is trimmed off leading and trailing whitespaces.
 */
private String fit(String input, Mapper mapper) {
    input = input.toUpperCase();
    Matcher matcher = fitting.matcher(input);

    StringBuffer buffer = new StringBuffer();
    while (!matcher.hitEnd() && matcher.find()) {
        mapper.prepare(input, matcher.group(), " ");
        mapper.update(matcher.start());
        matcher.appendReplacement(buffer, " ");
    }

    matcher.appendTail(buffer);
    return buffer.toString();
}
 
Example 16
Source File: FlickrUtils.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
private static SearchResult jsonSearch(JSONObject obj, String path) throws JSONException {
    Matcher m = objOrArray.matcher(path);
    SearchResult ret = new SearchResult();
    //ret.type = curEnum.obj;
    //ret.obj = obj;
    
    while(m.find()) {
        if(ret.obj == null) {
            ret.obj = obj;
        }
        else {
            if(ret.type == curEnum.obj)
                ret.obj = ret.obj.getJSONObject(ret.subName);
            else
                ret.obj = ret.arr.getJSONObject(ret.subIdx);
        }
        
        ret.subName = m.group();
        ret.type = curEnum.obj;
        
        if(m.hitEnd()) {
            break;
        }
        
        if(path.charAt(m.end()) == '.') {
            continue;
        }
        else {
            Matcher n = arrayIndex.matcher(path.subSequence(m.end() + 1, path.length()));
            if(!n.find())
                throw new JSONException(path);

            if(ret.type == curEnum.obj)
                ret.arr = ret.obj.getJSONArray(ret.subName);
            else
                ret.arr = ret.arr.getJSONArray(ret.subIdx);
            
            ret.subIdx = Integer.parseInt(n.group());
            ret.type = curEnum.arr;
            
            m.region(m.end() + 1 + n.end() + 1, path.length());
        }
    }
    return ret;
}
 
Example 17
Source File: StringFormatUtils.java    From datakernel with Apache License 2.0 4 votes vote down vote up
public static Duration parseDuration(String string) {
	string = string.trim();
	if (string.startsWith("-P") || string.startsWith("P")) {
		return Duration.parse(string);
	}
	Set<String> units = new HashSet<>();
	int days = 0, hours = 0, minutes = 0;
	long seconds = 0, millis = 0, nanos = 0;
	double doubleSeconds = 0.0;
	long result;

	Matcher matcher = DURATION_PATTERN.matcher(string.trim().toLowerCase());
	int lastEnd = 0;
	while (!matcher.hitEnd()) {
		if (!matcher.find() || matcher.start() != lastEnd) {
			throw new IllegalArgumentException("Invalid duration: " + string);
		}
		lastEnd = matcher.end();
		String unit = matcher.group("unit");
		if (!unit.endsWith("s")) {
			unit += "s";
		}
		if (!units.add(unit)) {
			throw new IllegalArgumentException("Time unit " + unit + " occurs more than once in: " + string);
		}

		result = Long.parseLong(matcher.group("time"));
		int numerator = 0;
		int denominator = 1;
		String floatingPoint = matcher.group("floating");
		if (floatingPoint != null) {
			if (unit.equals("nanos")) {
				throw new IllegalArgumentException("Time unit nanos cannot be fractional");
			}
			numerator = Integer.parseInt(floatingPoint);
			for (int i = 0; i < floatingPoint.length(); i++) {
				denominator *= 10;
			}
		}

		double fractional = (double) numerator / denominator;
		switch (unit) {
			case "days":
				days = (int) result;
				doubleSeconds += SECONDS_PER_DAY * fractional;
				break;
			case "hours":
				hours += (int) result;
				doubleSeconds += SECONDS_PER_HOUR * fractional;
				break;
			case "minutes":
				minutes += (int) result;
				doubleSeconds += SECONDS_PER_MINUTE * fractional;
				break;
			case "seconds":
				seconds += (int) result;
				doubleSeconds += fractional;
				break;
			case "millis":
				millis += result;
				doubleSeconds += fractional / MILLIS_IN_SECOND;
				break;
			case "nanos":
				nanos += result;
				break;
		}
	}

	return Duration.ofDays(days)
			.plusHours(hours)
			.plusMinutes(minutes)
			.plusSeconds(seconds)
			.plusMillis(millis)
			.plusNanos(nanos)
			.plusSeconds(round(doubleSeconds))
			.plusNanos(round((doubleSeconds - round(doubleSeconds)) * (NANOS_IN_MILLI * MILLIS_IN_SECOND)));
}
 
Example 18
Source File: PackageList.java    From mvn-golang with Apache License 2.0 4 votes vote down vote up
private Package(@Nonnull String textLine) throws ParseException {
  textLine = removeComment(textLine, false);

  final Matcher matcher = PATTERN.matcher(textLine);

  final Map<String, String> map = new HashMap<>();

  while (matcher.find()) {
    final String unknown = matcher.group(3);
    if (unknown != null) {
      throw new ParseException(textLine, matcher.start(3));
    }

    final String name = matcher.group(1).trim().toLowerCase(Locale.ENGLISH);
    final String value = matcher.group(2).trim();

    if (!ALLOWED_KEYS.contains(name)) {
      throw new IllegalArgumentException("Unsupported key: " + name);
    }

    if (map.containsKey(name)) {
      throw new ParseException(textLine, matcher.start(1));
    }

    map.put(name, value);
  }

  if (!matcher.hitEnd()) {
    throw new ParseException(textLine, 0);
  }

  if (!map.containsKey(TAG_PACKAGE)) {
    throw new IllegalArgumentException("Can't find package name : " + textLine);
  }

  this.pkg = map.get(TAG_PACKAGE);
  if (this.pkg.isEmpty()) {
    throw new IllegalArgumentException("Empty package name : " + textLine);
  }

  this.branch = map.get(TAG_BRANCH);
  this.tag = map.get(TAG_TAG);
  this.revision = map.get(TAG_REVISION);
}
 
Example 19
Source File: Utils.java    From ASTRAL with Apache License 2.0 4 votes vote down vote up
public static List<String> generateAllBinaryTreeStrings(String[] leaves){
	List<StringBuffer> alltrees = new ArrayList<StringBuffer>();
	List<String> results = new ArrayList<String>();
	System.err.print("Computing all possible resolutions ");
	int index = 0;
	//build a basic 3 leaf unrooted tree
	StringBuffer threeLeafTree = new StringBuffer();
	threeLeafTree.append("("+leaves[index++]+",("+leaves[index++]+","+leaves[index++]+"));");
	alltrees.add(threeLeafTree);

	for(;index<leaves.length; index++){
		String leaf = leaves[index];
		String insert = ","+leaf+")";
		List<StringBuffer> temp = new ArrayList<StringBuffer>();
		temp.addAll(alltrees);
		alltrees.clear();
		Stack<Integer> stacks = new Stack<Integer>();
		Stack<Integer> stacke = new Stack<Integer>();
		for(StringBuffer preTree: temp){
			Matcher pattern = Pattern.compile(
					"([(])|([)][^,:;)]*)|([;])|(:)|([^,);(:]*)").matcher(preTree);
			while(!pattern.hitEnd()){
				pattern.find();
				String token = pattern.group();
				while ("".equals(token)) {
					pattern.find();
					token = pattern.group();
				}
				if (")".equals(token)) {
					Integer c1s = stacks.pop();
					Integer c1e = stacke.pop();
					Integer c2s = stacks.pop();
					Integer c2e = stacke.pop();
					stacks.push(c2s-1);
					stacke.push(c1e+1);
					StringBuffer newTree1 = new StringBuffer(preTree);
					newTree1.insert(c2e, insert);
					newTree1.insert(c2s, "(");
					if (index == leaves.length - 1) {
						results.add(newTree1.toString());
					} else {
						alltrees.add(newTree1);
					}
					StringBuffer newTree2 = new StringBuffer(preTree);
					newTree2.insert(c1e, insert);
					newTree2.insert(c1s, "(");
					if (index == leaves.length - 1) {
						results.add(newTree2.toString());
					} else {
						alltrees.add(newTree2);
					}
				} else if (";".equals(token)) {
					if (index == leaves.length - 1) {
						results.remove(results.size() - 1);
					} else {
						alltrees.remove(alltrees.size() - 1);
					}
				} else if (!"(".equals(token) && !",".equals(token)) {
					stacks.push(pattern.start());
					stacke.push(pattern.end());
				} 
			}
			/*for (int i = preTree.indexOf(")", 0); i > 0; i = preTree.indexOf(")", i+1)) {
				
			}*/
		}
		temp.clear();
		System.err.print(".");
		System.err.flush();
	}
	System.err.println();

	/*List<Tree> temp = new ArrayList<Tree>();
	temp.addAll(alltrees);
	alltrees.clear();
	for(Tree unrootedTree: temp){
		alltrees.addAll(((STITree)unrootedTree).getAllRootingTrees());
	}
	temp.clear();*/
	return results;
}
 
Example 20
Source File: StringGroovyMethods.java    From groovy with Apache License 2.0 2 votes vote down vote up
/**
 * Given a matcher that matches a string against a pattern, returns true when
 * the string matches the pattern or if a longer string, could match the pattern.
 *
 * For example:
 * <pre class="groovyTestCase">
 *     def emailPattern = /\w+@\w+\.\w{2,}/
 *
 *     def matcher = "john@doe" =~ emailPattern
 *     assert matcher.matchesPartially()
 *
 *     matcher = "[email protected]" =~ emailPattern
 *     assert matcher.matchesPartially()
 *
 *     matcher = "john@@" =~ emailPattern
 *     assert !matcher.matchesPartially()
 * </pre>
 *
 * @param self the Matcher
 * @return true if more input to the String could make the matcher match the associated pattern, false otherwise.
 *
 * @since 2.0.0
 */
public static boolean matchesPartially(final Matcher self) {
    return self.matches() || self.hitEnd();
}