• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java Matcher类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中com.google.code.regexp.Matcher的典型用法代码示例。如果您正苦于以下问题:Java Matcher类的具体用法?Java Matcher怎么用?Java Matcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Matcher类属于com.google.code.regexp包,在下文中一共展示了Matcher类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: countEmojis

import com.google.code.regexp.Matcher; //导入依赖的package包/类
/**
 * Counts valid emojis passed string
 * 
 * @param text String to count emoji characters in.
 * @return returns count of emojis
 */
public static int countEmojis(String text) {

	String htmlifiedText = htmlify(text);
	// regex to identify html entitities in htmlified text
	Matcher matcher = htmlEntityPattern.matcher(htmlifiedText);

	int counter = 0;
	while (matcher.find()) {
		String emojiCode = matcher.group();
		if (isEmoji(emojiCode)) {
			counter++;
		}
	}
	return counter;
}
 
开发者ID:wax911,项目名称:anitrend-app,代码行数:22,代码来源:EmojiUtils.java


示例2: compileRegex

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public static String compileRegex(Route route, List<String> variables) {
    HashMap<String, String> requirements = route.getRequirements();
    Iterator<String> variablesIterator = variables.iterator();
    String patternString = quote(route.getPath());
    while (variablesIterator.hasNext()) {
        String varName = variablesIterator.next();
        String regex = "[^/]+";
        if (requirements.containsKey(varName)) {
            regex = requirements.get(varName);
        }
        patternString = patternString.replaceFirst(
                String.format("\\\\\\{%s\\\\\\}", varName),
                java.util.regex.Matcher.quoteReplacement(String.format("(?<%s>%s)", varName, regex))
        );
    }

    return patternString;
}
 
开发者ID:mr5,项目名称:android-router,代码行数:19,代码来源:RouteCompilerImpl.java


示例3: processTuple

import com.google.code.regexp.Matcher; //导入依赖的package包/类
/**
 * Parses string with regex, and emits a Map corresponding to named capturing group names and their captured values.
 *
 * @param line tuple to parse
 * @throws RuntimeException
 */
public void processTuple(String line) throws RuntimeException
{
  if (pattern == null) {
    throw new RuntimeException("regex has not been set");
  }

  Matcher matcher = pattern.matcher(line);
  if (matcher.matches()) {
    Map<String, Object> outputMap = new HashMap<String, Object>();

    for (String key : pattern.groupNames()) {
      outputMap.put(key, matcher.group(key));
    }
    output.emit(outputMap);
  }
}
 
开发者ID:apache,项目名称:apex-malhar,代码行数:23,代码来源:RegexMatchMapOperator.java


示例4: testMatchFiles_several_Regexp

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public void testMatchFiles_several_Regexp() {
    System.out.println("matchFiles_several_Regexp");

    Path file = Paths.get("src/test/resources/file.log");

    Map<String, String> regexpMap = new HashMap<>();
    Map<String, String> matchesMap = new HashMap<>();

    regexpMap.put("1", "(?<date>\\d{4}-\\d{2}-\\d{2}+)\\s");
    regexpMap.put("2", "(?<time>\\d{2}:\\d{2}:\\d{2}+)\\s");

    try {
        List<String> linesfile = Files.readAllLines(file, Charset.defaultCharset());
        for (String line : linesfile) {
            for (String regexp : regexpMap.values()) {
                Matcher m = Pattern.compile(regexp).matcher(line);
                matchesMap.putAll(m.namedGroups());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(matchesMap);

}
 
开发者ID:keedio,项目名称:flume-enrichment-interceptor-skeleton,代码行数:27,代码来源:RegexpDataTest.java


示例5: capturePathParms

import com.google.code.regexp.Matcher; //导入依赖的package包/类
private void capturePathParms(Properties parms, String path, Route route) {
  Matcher m = route._url_pattern.matcher(path);
  if (! m.matches()) {
    throw H2O.fail("Routing regex error: Pattern matched once but not again for pattern: " + route._url_pattern.pattern() + " and path: " + path);
  }

  // Java doesn't allow _ in group names but we want them in field names, so remove all _ from the path params before we look up the group capture value
  for (String key : route._path_params) {
    String key_no_underscore = key.replace("_","");
    String val;
    try {
      val = m.group(key_no_underscore);
    }
    catch (IllegalArgumentException e) {
      throw H2O.fail("Missing request parameter in the URL: did not find " + key + " in the URL as expected; URL pattern: " + route._url_pattern.pattern() + " with expected parameters: " + Arrays.toString(route._path_params) + " for URL: " + path);
    }
    if (null != val)
      parms.put(key, val);
  }
}
 
开发者ID:kyoren,项目名称:https-github.com-h2oai-h2o-3,代码行数:21,代码来源:RequestServer.java


示例6: setHexHtml

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public void setHexHtml(String hexHtml) {
	this.hexHtml = hexHtml;
	Matcher matcher = htmlSurrogateEntityPattern.matcher(hexHtml);
	if(matcher.find()) {
		String signifiantHtmlEntity = matcher.group("H");
		this.setHexHtmlShort(signifiantHtmlEntity);
	} else {
		this.setHexHtmlShort(hexHtml);
	}
}
 
开发者ID:wax911,项目名称:anitrend-app,代码行数:11,代码来源:Emoji.java


示例7: setDecimalHtml

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public void setDecimalHtml(String decimalHtml) {
	
	this.decimalHtml = decimalHtml;
	Matcher matcher = htmlSurrogateEntityPattern.matcher(decimalHtml);
	if(matcher.find()) {
		String signifiantHtmlEntity = matcher.group("H");
		this.setDecimalHtmlShort(signifiantHtmlEntity);
	} else {
		this.setDecimalHtmlShort(decimalHtml);
	}
}
 
开发者ID:wax911,项目名称:anitrend-app,代码行数:12,代码来源:Emoji.java


示例8: parsePathVariables

import com.google.code.regexp.Matcher; //导入依赖的package包/类
protected Map<String, String> parsePathVariables(CompiledRoute compiledRoute, Matcher matchedMatcher) {
    Map<String, String> pathVariables = null;
    if (compiledRoute.getVariables() != null) {
        pathVariables = new HashMap<>();
        for (String var : compiledRoute.getVariables()) {
            pathVariables.put(var, matchedMatcher.group(var));
        }
    }

    return pathVariables;
}
 
开发者ID:mr5,项目名称:android-router,代码行数:12,代码来源:UrlMatcherImpl.java


示例9: detectVariables

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public static List<String> detectVariables(Route route) {
    Pattern pattern = Pattern.compile("\\{(\\w+)\\}");
    Matcher matcher = pattern.matcher(route.getPath());
    List<String> variables = new ArrayList<>();
    while (matcher.find()) {
        variables.add(matcher.group(1));
    }

    return variables;
}
 
开发者ID:mr5,项目名称:android-router,代码行数:11,代码来源:RouteCompilerImpl.java


示例10: applyRegexps

import com.google.code.regexp.Matcher; //导入依赖的package包/类
/**
 * Aplicar regexps al mensaje, de todas las regexps enriquequecemos usando
 * la primera regexp que nos devuelva algun resultado.
 *
 * @param message
 * @return map
 */
public Map<String, String> applyRegexps(String message) {
    logger.debug("Message: " + message);


    for (Map.Entry<String, Pattern> entry : regexpMap.entrySet()) {
        logger.debug("Regexp: " + entry.getKey() + " |||| " + entry.getValue());
        Matcher m = entry.getValue().matcher(message);

        if (m.namedGroups().size() > 0) {
            logger.debug("WITH NAMED GROUPS");
            matchesMap.putAll(m.namedGroups());
            break;
        } else {
            logger.debug("WITHOUT NAMED GROUPS");
            // First match is already catched by previous namedGroups() call, so we reset it
            m.reset();
            // Useful for regexps with <key, value> pairs
            while (m.find() && m.groupCount() > 0){
                logger.debug("Group 0: " + m.group(0));
                logger.debug("Group 1: " + m.group(this.regexpKey));
                logger.debug("Group 2: " + m.group(this.regexpValue));
                matchesMap.put(m.group(this.regexpKey), m.group(this.regexpValue));
            }
        }
    }
    return matchesMap;
}
 
开发者ID:keedio,项目名称:flume-enrichment-interceptor-skeleton,代码行数:35,代码来源:RegexpData.java


示例11: testMatchFiles_SINGLE_Regexp

import com.google.code.regexp.Matcher; //导入依赖的package包/类
/**
 * Test of matchFilesRegexp(), of class RegexpData
 */
public void testMatchFiles_SINGLE_Regexp() {
    System.out.println("matchFiles_single_Regexp");

    Path file = Paths.get("src/test/resources/file.log");

    Map<String, String> regexpMap = new HashMap<>();
    Map<String, String> matchesMap = new HashMap<>();

    regexpMap.put("1", "(?<date>\\d{4}-\\d{2}-\\d{2}+)\\s"
            + "(?<time>\\d{2}:\\d{2}:\\d{2}+)\\s"
            + "(?<time-taken>\\d{1}+)\\s");

    try {
        List<String> linesfile = Files.readAllLines(file, Charset.defaultCharset());
        for (String line : linesfile) {
            for (String regexp : regexpMap.values()) {
                Matcher m = Pattern.compile(regexp).matcher(line);
                matchesMap.putAll(m.namedGroups());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(matchesMap);

}
 
开发者ID:keedio,项目名称:flume-enrichment-interceptor-skeleton,代码行数:31,代码来源:RegexpDataTest.java


示例12: testMatchFiles_SINGLE_Regexp_SEVERAL_lines

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public void testMatchFiles_SINGLE_Regexp_SEVERAL_lines() {
    System.out.println("MatchFiles_SINGLE_Regexp_SEVERAL_lines_Single_file");

    Path file = Paths.get("src/test/resources/file3.log");

    Map<String, String> regexpMap = new HashMap<>();
    Map<String, String> matchesMap = new HashMap<>();

    regexpMap.put("1", "(?<date>\\d{4}-\\d{2}-\\d{2}+)\\s"
            + "(?<time>\\d{2}:\\d{2}:\\d{2}+)\\s"
            + "(?<time-taken>\\d{1}+)\\s");

    try {
        List<String> linesfile = Files.readAllLines(file, Charset.defaultCharset());
        for (String line : linesfile) {
            for (String regexp : regexpMap.values()) {
                Matcher m = Pattern.compile(regexp).matcher(line);
                matchesMap.putAll(m.namedGroups());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(matchesMap);

}
 
开发者ID:keedio,项目名称:flume-enrichment-interceptor-skeleton,代码行数:28,代码来源:RegexpDataTest.java


示例13: getInlineDirectiveMatchers

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public List<InlineDirectiveMatcher> getInlineDirectiveMatchers(String text) {
	List<InlineDirectiveMatcher> matchers = new ArrayList<InlineDirectiveMatcher>();
	for( InlineDirectiveItem directive : inlineDirectives ){
		Matcher m = directive.pattern.matcher(text);
		matchers.add(new InlineDirectiveMatcher(m, directive.directiveClass));
	}
	return matchers;
}
 
开发者ID:cupmanager,项目名称:jangular,代码行数:9,代码来源:DirectiveRepository.java


示例14: getEmoji

import com.google.code.regexp.Matcher; //导入依赖的package包/类
/**
 * Get emoji by unicode, short code, decimal html entity or hexadecimal html
 * entity
 * 
 * @param code unicode, short code, decimal html entity or hexadecimal html
 * @return Emoji
 */
public static Emoji getEmoji(String code) {

	Matcher m = shortCodePattern.matcher(code);
	

	// test for shortcode with colons
	if (m.find()) {
		code = m.group(1);
	}

	Emoji emoji = null;
	// If you're running java 8 you could do this:
       /*selectFirst(EmojiManager.data(),having(on(Emoji.class).getEmoji(), Matchers.equalTo(code))
                       .or(having(on(Emoji.class).getEmoji(), Matchers.equalTo(code)))
					.or(having(on(Emoji.class).getHexHtml(), Matchers.equalToIgnoringCase(code)))
					.or(having(on(Emoji.class).getDecimalHtml(), Matchers.equalToIgnoringCase(code)))
					.or(having(on(Emoji.class).getDecimalSurrogateHtml(), Matchers.equalToIgnoringCase(code)))
					.or(having(on(Emoji.class).getHexHtmlShort(), Matchers.equalToIgnoringCase(code)))
					.or(having(on(Emoji.class).getDecimalHtmlShort(), Matchers.equalToIgnoringCase(code)))
					.or(having(on(Emoji.class).getAliases(), Matchers.hasItem(code)))
					.or(having(on(Emoji.class).getEmoticons(), Matchers.hasItem(code))));*/

       // since i'm using Java 7 if not you can just do as follows:
       /*
       * I'll be excluding Aliases e.g. "smiley" and Emoticons e.g. :/ because they interfere with links such as http[":/"]/
	* Matchers.hasItem(code).matches(emo.getEmoticons())
       **/
	for (Emoji emo: EmojiManager.data()) {
		if (Matchers.equalTo(code).matches(emo.getEmoji()) ||
				Matchers.equalToIgnoringCase(code).matches(emo.getEmoji()) ||
				Matchers.equalToIgnoringCase(code).matches(emo.getHexHtml()) ||
				Matchers.equalToIgnoringCase(code).matches(emo.getDecimalHtml()) ||
				Matchers.equalToIgnoringCase(code).matches(emo.getDecimalSurrogateHtml()) ||
				Matchers.equalToIgnoringCase(code).matches(emo.getHexHtmlShort()) ||
				Matchers.equalToIgnoringCase(code).matches(emo.getDecimalHtmlShort()) ||
                   Matchers.hasItem(code).matches(emo.getAliases())) {
			emoji = emo;
			break;
		}
	}

	return emoji;
}
 
开发者ID:wax911,项目名称:anitrend-app,代码行数:51,代码来源:EmojiUtils.java


示例15: processStringWithRegex

import com.google.code.regexp.Matcher; //导入依赖的package包/类
/**
 * Common method used for processing the string to replace with emojis
 * 
 * @param text
 * @param pattern
 * @return
 */
private static String processStringWithRegex(String text, Pattern pattern, int startIndex, boolean recurseEmojify) {
	//System.out.println(text);
	Matcher matcher = pattern.matcher(text);
	StringBuffer sb = new StringBuffer();
	int resetIndex = 0;
	
	if(startIndex > 0) {
		matcher.region(startIndex, text.length());
	} 
	
	while (matcher.find()) {
		
		String emojiCode = matcher.group();
		
		Emoji emoji = getEmoji(emojiCode);
		// replace matched tokens with emojis
		
		if(emoji!=null) {
			matcher.appendReplacement(sb, emoji.getEmoji());
		} else {
			if(htmlSurrogateEntityPattern2.matcher(emojiCode).matches()) {
				String highSurrogate1 = matcher.group("H1");
				String highSurrogate2 = matcher.group("H2");
				String lowSurrogate1 = matcher.group("L1");
				String lowSurrogate2 = matcher.group("L2");
				matcher.appendReplacement(sb, processStringWithRegex(highSurrogate1+highSurrogate2, shortCodeOrHtmlEntityPattern, 0, false));
				
				//basically this handles &#junk1;&#10084;&#65039;&#junk2; scenario
				//verifies if &#junk1;&#10084; or &#junk1; are valid emojis via recursion
				//if not move past &#junk1; and reset the cursor to &#10084;
				if(sb.toString().endsWith(highSurrogate2)) {
					resetIndex = sb.length() - highSurrogate2.length();
				} else {
					resetIndex = sb.length();
				}
				sb.append(lowSurrogate1);
				sb.append(lowSurrogate2);
				break;
			} else if(htmlSurrogateEntityPattern.matcher(emojiCode).matches()) {
				//could be individual html entities assumed as surrogate pair
				String highSurrogate = matcher.group("H");
				String lowSurrogate = matcher.group("L");
				matcher.appendReplacement(sb, processStringWithRegex(highSurrogate, htmlEntityPattern, 0, true));
				resetIndex = sb.length();
				sb.append(lowSurrogate);
				break;
			} else {
				matcher.appendReplacement(sb, emojiCode);
			}
		}

	}
	matcher.appendTail(sb);
	
	//do not recurse emojify when coming here through htmlSurrogateEntityPattern2..so we get a chance to check if the tail
	//is part of a surrogate entity
	if(recurseEmojify && resetIndex > 0) {
		return emojify(sb.toString(), resetIndex);
	}
	return sb.toString();
}
 
开发者ID:wax911,项目名称:anitrend-app,代码行数:69,代码来源:EmojiUtils.java


示例16: InlineDirectiveMatcher

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public InlineDirectiveMatcher(Matcher matcher, Class<? extends AbstractDirective<?>> directiveClass) {
	this.matcher = matcher;
	this.directiveClass = directiveClass;
}
 
开发者ID:cupmanager,项目名称:jangular,代码行数:5,代码来源:DirectiveRepository.java


示例17: compile

import com.google.code.regexp.Matcher; //导入依赖的package包/类
/**
 * Compile the {@code Grok} pattern to named regex pattern.
 *
 * @param pattern : Grok pattern (ex: %{IP})
 * @throws Exception
 */
public void compile(String pattern) throws Exception {

  if (StringUtils.isBlank(pattern)) {
    throw new Exception("{pattern} should not be empty or null");
  }

  namedRegex = pattern;
  originalGrokPattern = pattern;
  int index = 0;
  /** flag for infinite recurtion */
  int iterationLeft = 1000;
  Boolean continueIteration = true;

  // Replace %{foo} with the regex (mostly groupname regex)
  // and then compile the regex
  while (continueIteration) {
    continueIteration = false;
    if (iterationLeft <= 0) {
      throw new Exception("Deep recursion pattern compilation of " + originalGrokPattern);
    }
    iterationLeft--;

    Matcher m = GrokUtils.GROK_PATTERN.matcher(namedRegex);
    // Match %{Foo:bar} -> pattern name and subname
    // Match %{Foo=regex} -> add new regex definition
    if (m.find()) {
      continueIteration = true;
      Map<String, String> group = m.namedGroups();
      if (group.get("definition") != null) {
        try {
          addPattern(group.get("pattern"), group.get("definition"));
          group.put("name", group.get("name") + "=" + group.get("definition"));
        } catch (Exception e) {
          // Log the exeception
        }
      }
      namedRegexCollection.put("name" + index,
          (group.get("subname") != null ? group.get("subname") : group.get("name")));
      namedRegex =
          StringUtils.replace(namedRegex, "%{" + group.get("name") + "}", "(?<name" + index + ">"
              + grokPatternDefinition.get(group.get("pattern")) + ")");
      // System.out.println(_expanded_pattern);
      index++;
    }
  }

  if (namedRegex.isEmpty()) {
    throw new Exception("Pattern not fount");
  }
  // Compile the regex
  compiledNamedRegex = Pattern.compile(namedRegex);
}
 
开发者ID:OpenSOC,项目名称:opensoc-streaming,代码行数:59,代码来源:OpenSOCGrok.java


示例18: getMatch

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public Matcher getMatch() {
  return match;
}
 
开发者ID:OpenSOC,项目名称:opensoc-streaming,代码行数:4,代码来源:OpenSOCMatch.java


示例19: setMatch

import com.google.code.regexp.Matcher; //导入依赖的package包/类
public void setMatch(Matcher match) {
  this.match = match;
}
 
开发者ID:OpenSOC,项目名称:opensoc-streaming,代码行数:4,代码来源:OpenSOCMatch.java


示例20: extractNamedGroups

import com.google.code.regexp.Matcher; //导入依赖的package包/类
/**
 * Extracts named groups from the raw data
 *
 * @param rawData
 * @return A map of group names mapped to their extracted values or null if there are no matches
 */
public Map<String, String> extractNamedGroups(final CharSequence rawData) {

  Matcher matcher = compiledPattern.matcher(rawData);

  if (matcher.find()) {

    MatchResult r = matcher.toMatchResult();

    if (r != null && r.namedGroups() != null) {
      return r.namedGroups();
    }
  }

  return null;
}
 
开发者ID:aicer,项目名称:grok,代码行数:22,代码来源:Grok.java



注:本文中的com.google.code.regexp.Matcher类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java BaseApplication类代码示例发布时间:2022-05-23
下一篇:
Java InvocationType类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap