java.util.regex.Matcher#region ( )源码实例Demo

下面列出了java.util.regex.Matcher#region ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: reader   文件: MediaType.java
/**
 * Returns a media type for {@code string}, or null if {@code string} is not a
 * well-formed media type.
 */
public static MediaType parse(String string) {
  Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
  if (!typeSubtype.lookingAt()) return null;
  String type = typeSubtype.group(1).toLowerCase(Locale.US);
  String subtype = typeSubtype.group(2).toLowerCase(Locale.US);

  String charset = null;
  Matcher parameter = PARAMETER.matcher(string);
  for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
    parameter.region(s, string.length());
    if (!parameter.lookingAt()) return null; // This is not a well-formed media type.

    String name = parameter.group(1);
    if (name == null || !name.equalsIgnoreCase("charset")) continue;
    if (charset != null) throw new IllegalArgumentException("Multiple charsets: " + string);
    charset = parameter.group(2) != null
        ? parameter.group(2)  // Value is a token.
        : parameter.group(3); // Value is a quoted string.
  }

  return new MediaType(string, type, subtype, charset);
}
 
源代码2 项目: CordovaYoutubeVideoPlayer   文件: MediaType.java
/**
 * Returns a media type for {@code string}, or null if {@code string} is not a
 * well-formed media type.
 */
public static MediaType parse(String string) {
  Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
  if (!typeSubtype.lookingAt()) return null;
  String type = typeSubtype.group(1).toLowerCase(Locale.US);
  String subtype = typeSubtype.group(2).toLowerCase(Locale.US);

  String charset = null;
  Matcher parameter = PARAMETER.matcher(string);
  for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
    parameter.region(s, string.length());
    if (!parameter.lookingAt()) return null; // This is not a well-formed media type.

    String name = parameter.group(1);
    if (name == null || !name.equalsIgnoreCase("charset")) continue;
    if (charset != null) throw new IllegalArgumentException("Multiple charsets: " + string);
    charset = parameter.group(2) != null
        ? parameter.group(2)  // Value is a token.
        : parameter.group(3); // Value is a quoted string.
  }

  return new MediaType(string, type, subtype, charset);
}
 
源代码3 项目: cordova-amazon-fireos   文件: MediaType.java
/**
 * Returns a media type for {@code string}, or null if {@code string} is not a
 * well-formed media type.
 */
public static MediaType parse(String string) {
  Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
  if (!typeSubtype.lookingAt()) return null;
  String type = typeSubtype.group(1).toLowerCase(Locale.US);
  String subtype = typeSubtype.group(2).toLowerCase(Locale.US);

  String charset = null;
  Matcher parameter = PARAMETER.matcher(string);
  for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
    parameter.region(s, string.length());
    if (!parameter.lookingAt()) return null; // This is not a well-formed media type.

    String name = parameter.group(1);
    if (name == null || !name.equalsIgnoreCase("charset")) continue;
    if (charset != null) throw new IllegalArgumentException("Multiple charsets: " + string);
    charset = parameter.group(2) != null
        ? parameter.group(2)  // Value is a token.
        : parameter.group(3); // Value is a quoted string.
  }

  return new MediaType(string, type, subtype, charset);
}
 
源代码4 项目: java-mammoth   文件: RegexTokeniser.java
public List<Token<T>> tokenise(String value) {
    Matcher matcher = pattern.matcher(value);
    List<Token<T>> tokens = new ArrayList<>();
    while (matcher.lookingAt()) {
        Optional<Integer> groupIndex = tryFind(intRange(0, this.rules.size()), index -> !isNull(matcher.group(index + 1)));
        if (groupIndex.isPresent()) {
            T tokenType = this.rules.get(groupIndex.get());
            tokens.add(new Token<>(matcher.regionStart(), tokenType, matcher.group()));
            matcher.region(matcher.end(), value.length());
        } else {
            // Should be impossible
            throw new RuntimeException("Could not find group");
        }
    }
    return tokens;
}
 
源代码5 项目: commonmark-java   文件: InlineParserImpl.java
/**
 * If RE matches at current index in the input, advance index and return the match; otherwise return null.
 */
private String match(Pattern re) {
    if (index >= input.length()) {
        return null;
    }
    try {
        Matcher matcher = re.matcher(input);
        matcher.region(index, input.length());
        boolean m = matcher.find();
        if (m) {
            index = matcher.end();
            return matcher.group();
        } else {
            return null;
        }
    } catch (StackOverflowError e) {
        return null;
    }
}
 
源代码6 项目: phonegapbootcampsite   文件: MediaType.java
/**
 * Returns a media type for {@code string}, or null if {@code string} is not a
 * well-formed media type.
 */
public static MediaType parse(String string) {
  Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
  if (!typeSubtype.lookingAt()) return null;
  String type = typeSubtype.group(1).toLowerCase(Locale.US);
  String subtype = typeSubtype.group(2).toLowerCase(Locale.US);

  String charset = null;
  Matcher parameter = PARAMETER.matcher(string);
  for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
    parameter.region(s, string.length());
    if (!parameter.lookingAt()) return null; // This is not a well-formed media type.

    String name = parameter.group(1);
    if (name == null || !name.equalsIgnoreCase("charset")) continue;
    if (charset != null) throw new IllegalArgumentException("Multiple charsets: " + string);
    charset = parameter.group(2) != null
        ? parameter.group(2)  // Value is a token.
        : parameter.group(3); // Value is a quoted string.
  }

  return new MediaType(string, type, subtype, charset);
}
 
源代码7 项目: Markwon   文件: MarkwonInlineParser.java
/**
 * If RE matches at current index in the input, advance index and return the match; otherwise return null.
 */
@Override
@Nullable
public String match(@NonNull Pattern re) {
    if (index >= input.length()) {
        return null;
    }
    Matcher matcher = re.matcher(input);
    matcher.region(index, input.length());
    boolean m = matcher.find();
    if (m) {
        index = matcher.end();
        return matcher.group();
    } else {
        return null;
    }
}
 
源代码8 项目: OpenEphyra   文件: AnswerPattern.java
/**
 * Applies the pattern to a sentence of space-delimited tokens containing
 * a TARGET tag and optionally a number of CONTEXT and NE tags. For each
 * match, a PROPERTY object is extracted.
 * 
 * @param sentence a sentence
 * @return array of PROPERTY objects or an empty array, if the sentence does
 *         not match the pattern
 */
public String[] apply(String sentence) {
	Matcher m = pattern.matcher(sentence);
	ArrayList<String> results = new ArrayList<String>();
	
	while (m.find()) {
		if (m.group(distID).split(" ").length <= MAX_DIST)
			// distance between TARGET and PROPERTY is restricted to
			// MAX_DIST tokens (Note: NEs are counted as 1)
			results.add(m.group(propertyID));
		
		// continue search right after the beginning of this match
		m.region(m.start() + 1, sentence.length());
	}
	
	return results.toArray(new String[results.size()]);
}
 
源代码9 项目: j2objc   文件: MatcherTest.java
public void testFindRegionChanged() {
    // Regression for HARMONY-625
    // Verify if the Matcher behaves correct when region is changed.
    Pattern pattern = Pattern.compile("(?s).*");
    Matcher matcher = pattern.matcher("abcde");
    matcher.find();
    assertEquals("abcde", matcher.group());

    matcher = pattern.matcher("abcde");
    matcher.region(0, 2);
    matcher.find();
    assertEquals("ab", matcher.group());

}
 
源代码10 项目: Telegram-FOSS   文件: FastDateParser.java
/**
 * Initialize derived fields from defining fields.
 * This is called from constructor and from readObject (de-serialization)
 *
 * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
 */
private void init(Calendar definingCalendar) {

    final StringBuilder regex = new StringBuilder();
    final List<Strategy> collector = new ArrayList<Strategy>();

    final Matcher patternMatcher = formatPattern.matcher(pattern);
    if (!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException(
                "Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'");
    }

    currentFormatField = patternMatcher.group();
    Strategy currentStrategy = getStrategy(currentFormatField, definingCalendar);
    for (; ; ) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if (!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        final String nextFormatField = patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField, definingCalendar);
        if (currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField = nextFormatField;
        currentStrategy = nextStrategy;
    }
    if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
        throw new IllegalArgumentException("Failed to parse \"" + pattern + "\" ; gave up at index " + patternMatcher.regionStart());
    }
    if (currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField = null;
    strategies = collector.toArray(new Strategy[collector.size()]);
    parsePattern = Pattern.compile(regex.toString());
}
 
源代码11 项目: jus   文件: MediaType.java
/**
 * Returns a media type for {@code string}, or null if {@code string} is not a
 * well-formed media type.
 */
public static MediaType parse(String string) {
    if(string==null) return null;

    Map<String, String> params =  new HashMap<>();
    Matcher typeSubtype = TYPE_SUBTYPE.matcher(string);
    if (!typeSubtype.lookingAt()) return null;
    String type = typeSubtype.group(1).toLowerCase(Locale.US);
    String subtype = typeSubtype.group(2).toLowerCase(Locale.US);

    String charset = null;
    Matcher parameter = PARAMETER.matcher(string);
    for (int s = typeSubtype.end(); s < string.length(); s = parameter.end()) {
        parameter.region(s, string.length());
        if (!parameter.lookingAt()) return null; // This is not a well-formed media type.

        String name = parameter.group(1);
        if (name == null) continue;
        String param = parameter.group(2) != null
                ? parameter.group(2)  // Value is a token.
                : parameter.group(3); // Value is a quoted string.
        if(name.equalsIgnoreCase("charset")) {
            if (charset != null && !param.equalsIgnoreCase(charset)) {
                throw new IllegalArgumentException("Multiple different charsets: " + string);
            }
            charset = param;
        } else {
            params.put(name, param);
        }
    }
    return new MediaType(string, type, subtype, charset, Collections.unmodifiableMap(params));
}
 
源代码12 项目: JavaWeb   文件: StringUtil.java
public static String replaceByRegex(String origin,String replaceStr,String regex){
	Matcher matcher = Pattern.compile(regex).matcher(origin);
	matcher.useTransparentBounds(true).useAnchoringBounds(false);
	int pos = 0;
	int endPos = origin.length();
	while (pos < endPos) {
		matcher.region(pos, endPos);
		if (matcher.lookingAt()) {
			//System.out.println("修改前的为:"+matcher.group(1));
			origin = origin.replaceAll(matcher.group(1), replaceStr);
			pos = matcher.end();
		}
	}
	return origin;
}
 
源代码13 项目: coming   文件: JGenProg2017_0013_t.java
/**
 * Initialize derived fields from defining fields.
 * This is called from constructor and from readObject (de-serialization)
 */
private void init() {
    thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);

    nameValues= new ConcurrentHashMap<Integer, KeyValue[]>();

    StringBuilder regex= new StringBuilder();
    List<Strategy> collector = new ArrayList<Strategy>();

    Matcher patternMatcher= formatPattern.matcher(pattern);
    if(!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException("Invalid pattern");
    }

    currentFormatField= patternMatcher.group();
    Strategy currentStrategy= getStrategy(currentFormatField);
    for(;;) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if(!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        String nextFormatField= patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField);
        if(currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField= nextFormatField;
        currentStrategy= nextStrategy;
    }
    if(currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField= null;
    strategies= collector.toArray(new Strategy[collector.size()]);
    parsePattern= Pattern.compile(regex.toString());
}
 
源代码14 项目: coming   文件: Lang_10_FastDateParser_s.java
/**
 * Initialize derived fields from defining fields.
 * This is called from constructor and from readObject (de-serialization)
 */
private void init() {
    thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);

    nameValues= new ConcurrentHashMap<Integer, KeyValue[]>();

    StringBuilder regex= new StringBuilder();
    List<Strategy> collector = new ArrayList<Strategy>();

    Matcher patternMatcher= formatPattern.matcher(pattern);
    if(!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException("Invalid pattern");
    }

    currentFormatField= patternMatcher.group();
    Strategy currentStrategy= getStrategy(currentFormatField);
    for(;;) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if(!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        String nextFormatField= patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField);
        if(currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField= nextFormatField;
        currentStrategy= nextStrategy;
    }
    if(currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField= null;
    strategies= collector.toArray(new Strategy[collector.size()]);
    parsePattern= Pattern.compile(regex.toString());
}
 
源代码15 项目: keycloak   文件: OIDCAttributeMapperHelper.java
public static List<String> splitClaimPath(String claimPath) {
    final LinkedList<String> claimComponents = new LinkedList<>();
    Matcher m = CLAIM_COMPONENT.matcher(claimPath);
    int start = 0;
    while (m.find()) {
        claimComponents.add(BACKSLASHED_CHARACTER.matcher(m.group(1)).replaceAll("$1"));
        start = m.end();
        // This is necessary to match the start of region as the start of string as determined by ^
        m.region(start, claimPath.length());
    }
    if (claimPath.length() > start) {
        claimComponents.add(BACKSLASHED_CHARACTER.matcher(claimPath.substring(start)).replaceAll("$1"));
    }
    return claimComponents;
}
 
源代码16 项目: HolandaCatalinaFw   文件: Strings.java
/**
 * 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;
}
 
源代码17 项目: astor   文件: FastDateParser.java
/**
 * Initialize derived fields from defining fields.
 * This is called from constructor and from readObject (de-serialization)
 */
private void init() {
    final Calendar definingCalendar = Calendar.getInstance(timeZone, locale);
    thisYear= definingCalendar.get(Calendar.YEAR);

    final StringBuilder regex= new StringBuilder();
    final List<Strategy> collector = new ArrayList<Strategy>();

    final Matcher patternMatcher= formatPattern.matcher(pattern);
    if(!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException(
                "Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'");
    }

    currentFormatField= patternMatcher.group();
    Strategy currentStrategy= getStrategy(currentFormatField, definingCalendar);
    for(;;) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if(!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        final String nextFormatField= patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField, definingCalendar);
        if(currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField= nextFormatField;
        currentStrategy= nextStrategy;
    }
    if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
        throw new IllegalArgumentException("Failed to parse \""+pattern+"\" ; gave up at index "+patternMatcher.regionStart());
    }
    if(currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField= null;
    strategies= collector.toArray(new Strategy[collector.size()]);
    parsePattern= Pattern.compile(regex.toString());
}
 
源代码18 项目: coming   文件: Cardumen_0096_s.java
/**
 * Initialize derived fields from defining fields.
 * This is called from constructor and from readObject (de-serialization)
 */
private void init() {
    thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);

    nameValues= new ConcurrentHashMap<Integer, KeyValue[]>();

    StringBuilder regex= new StringBuilder();
    List<Strategy> collector = new ArrayList<Strategy>();

    Matcher patternMatcher= formatPattern.matcher(pattern);
    if(!patternMatcher.lookingAt()) {
        throw new IllegalArgumentException("Invalid pattern");
    }

    currentFormatField= patternMatcher.group();
    Strategy currentStrategy= getStrategy(currentFormatField);
    for(;;) {
        patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
        if(!patternMatcher.lookingAt()) {
            nextStrategy = null;
            break;
        }
        String nextFormatField= patternMatcher.group();
        nextStrategy = getStrategy(nextFormatField);
        if(currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField= nextFormatField;
        currentStrategy= nextStrategy;
    }
    if(currentStrategy.addRegex(this, regex)) {
        collector.add(currentStrategy);
    }
    currentFormatField= null;
    strategies= collector.toArray(new Strategy[collector.size()]);
    parsePattern= Pattern.compile(regex.toString());
}
 
源代码19 项目: styT   文件: Cookie.java
/** Parse a date as specified in RFC 6265, section 5.1.1. */
private static long parseExpires(String s, int pos, int limit) {
  pos = dateCharacterOffset(s, pos, limit, false);

  int hour = -1;
  int minute = -1;
  int second = -1;
  int dayOfMonth = -1;
  int month = -1;
  int year = -1;
  Matcher matcher = TIME_PATTERN.matcher(s);

  while (pos < limit) {
    int end = dateCharacterOffset(s, pos + 1, limit, true);
    matcher.region(pos, end);

    if (hour == -1 && matcher.usePattern(TIME_PATTERN).matches()) {
      hour = Integer.parseInt(matcher.group(1));
      minute = Integer.parseInt(matcher.group(2));
      second = Integer.parseInt(matcher.group(3));
    } else if (dayOfMonth == -1 && matcher.usePattern(DAY_OF_MONTH_PATTERN).matches()) {
      dayOfMonth = Integer.parseInt(matcher.group(1));
    } else if (month == -1 && matcher.usePattern(MONTH_PATTERN).matches()) {
      String monthString = matcher.group(1).toLowerCase(Locale.US);
      month = MONTH_PATTERN.pattern().indexOf(monthString) / 4; // Sneaky! jan=1, dec=12.
    } else if (year == -1 && matcher.usePattern(YEAR_PATTERN).matches()) {
      year = Integer.parseInt(matcher.group(1));
    }

    pos = dateCharacterOffset(s, end + 1, limit, false);
  }

  // Convert two-digit years into four-digit years. 99 becomes 1999, 15 becomes 2015.
  if (year >= 70 && year <= 99) year += 1900;
  if (year >= 0 && year <= 69) year += 2000;

  // If any partial is omitted or out of range, return -1. The date is impossible. Note that leap
  // seconds are not supported by this syntax.
  if (year < 1601) throw new IllegalArgumentException();
  if (month == -1) throw new IllegalArgumentException();
  if (dayOfMonth < 1 || dayOfMonth > 31) throw new IllegalArgumentException();
  if (hour < 0 || hour > 23) throw new IllegalArgumentException();
  if (minute < 0 || minute > 59) throw new IllegalArgumentException();
  if (second < 0 || second > 59) throw new IllegalArgumentException();

  Calendar calendar = new GregorianCalendar(UTC);
  calendar.setLenient(false);
  calendar.set(Calendar.YEAR, year);
  calendar.set(Calendar.MONTH, month - 1);
  calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
  calendar.set(Calendar.HOUR_OF_DAY, hour);
  calendar.set(Calendar.MINUTE, minute);
  calendar.set(Calendar.SECOND, second);
  calendar.set(Calendar.MILLISECOND, 0);
  return calendar.getTimeInMillis();
}
 
源代码20 项目: vscode-as3mxml   文件: CodeActionsUtils.java
public static AddImportData findAddImportData(String fileText, ImportRange importRange)
{
    int startIndex = importRange.startIndex;
    int endIndex = importRange.endIndex;
    if(startIndex == -1)
    {
        startIndex = 0;
    }
    int textLength = fileText.length();
    if (endIndex == -1 || endIndex > textLength)
    {
        //it's possible for the end index to be longer than the text
        //for example, if the package block is incomplete in an .as file
        endIndex = textLength;
    }
    String indent = "";
    String lineBreaks = "\n";
    int importIndex = -1;
    Matcher importMatcher = importPattern.matcher(fileText);
    importMatcher.region(startIndex, endIndex);
    while (importMatcher.find())
    {
        indent = importMatcher.group(1);
        importIndex = importMatcher.start();
    }
    Position position = null;
    if(importIndex != -1) //found existing imports
    {
        position = LanguageServerCompilerUtils.getPositionFromOffset(new StringReader(fileText), importIndex);
        position.setLine(position.getLine() + 1);
        position.setCharacter(0);
    }
    else //no existing imports
    {
        if(importRange.needsMXMLScript)
        {
            position = LanguageServerCompilerUtils.getPositionFromOffset(new StringReader(fileText), importRange.endIndex);
        }
        else
        {
            //start by looking for the package block
            Matcher packageMatcher = packagePattern.matcher(fileText);
            packageMatcher.region(startIndex, endIndex);
            if (packageMatcher.find()) //found the package
            {
                position = LanguageServerCompilerUtils.getPositionFromOffset(
                    new StringReader(fileText), packageMatcher.end());
                if(position.getCharacter() > 0)
                {
                    //go to the beginning of the line, if we're not there
                    position.setCharacter(0);
                }
                indent = packageMatcher.group(1);
            }
            else //couldn't find the start of a package or existing imports
            {
                position = LanguageServerCompilerUtils.getPositionFromOffset(new StringReader(fileText), startIndex);
                if (position.getCharacter() > 0)
                {
                    //go to the next line, if we're not at the start
                    position.setLine(position.getLine() + 1);
                    position.setCharacter(0);
                }
                //try to use the same indent as whatever follows
                Matcher indentMatcher = indentPattern.matcher(fileText);
                indentMatcher.region(startIndex, endIndex);
                if (indentMatcher.find())
                {
                    indent = indentMatcher.group(1);
                }
            }
        }
        lineBreaks += "\n"; //add an extra line break
    }
    return new AddImportData(position, indent, lineBreaks, importRange);
}