Java Code Examples for java.util.regex.Pattern#matcher()
The following examples show how to use
java.util.regex.Pattern#matcher() .
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: MatcherTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testOverFlow() { Pattern tp = Pattern.compile("(a*)*"); Matcher tm = tp.matcher("aaa"); assertTrue(tm.matches()); assertEquals("", tm.group(1)); assertTrue(Pattern.matches("(1+)\\1+", "11")); assertTrue(Pattern.matches("(1+)(2*)\\2+", "11")); Pattern pat = Pattern.compile("(1+)\\1*"); Matcher mat = pat.matcher("11"); assertTrue(mat.matches()); assertEquals("11", mat.group(1)); pat = Pattern.compile("((1+)|(2+))(\\2+)"); mat = pat.matcher("11"); assertTrue(mat.matches()); assertEquals("1", mat.group(2)); assertEquals("1", mat.group(1)); assertEquals("1", mat.group(4)); assertNull(mat.group(3)); }
Example 2
Source File: CreateActions.java From development with Apache License 2.0 | 6 votes |
@StateMachineAction public String createInstanceName(String instanceId, ProvisioningSettings settings, @SuppressWarnings("unused") InstanceStatus result) throws Exception { VMPropertyHandler ph = new VMPropertyHandler(settings); String regex = ph .getServiceSetting(VMPropertyHandler.TS_INSTANCENAME_PATTERN); if (regex != null) { String instanceName = ph.getInstanceName(); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(instanceName); if (!m.matches()) { logger.error("Validation error on instance name: [" + instanceName + "/" + regex + "] for instanceId" + instanceId); throw new APPlatformException( Messages.getAll("error_invalid_name", new Object[] { instanceName, regex })); } } return EVENT_SUCCESS; }
Example 3
Source File: MarkwonInlineParser.java From Markwon with Apache License 2.0 | 6 votes |
/** * 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; } }
Example 4
Source File: CosemValue.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
/** * Sets the value of this CosemValue * <p> * This method will automatically parse the unit and the value of the COSEM * value string * * @param cosemValue * the cosemValue * @throws ParseException * if parsing failed */ public void setValue(String cosemValue) throws ParseException { if (unit.length() > 0) { // Check if COSEM value has a unit, check and parse the value Pattern p = Pattern.compile("(.*)\\*" + unit); Matcher m = p.matcher(cosemValue); if (m.matches()) { value = parse(m.group(1)); } else { throw new ParseException("Unit of " + cosemValue + " is not " + unit, 0); } } else { // COSEM value does not have a unit, parse value value = parse(cosemValue); } }
Example 5
Source File: QueryTableCellRenderer.java From netbeans with Apache License 2.0 | 6 votes |
private static String highLight(String s, Pattern pattern) { Matcher matcher = pattern.matcher(s); int idx = 0; StringBuilder sb = new StringBuilder(); while (matcher.find(idx)) { int start = matcher.start(); int end = matcher.end(); if (start == end) { break; } sb.append(s.substring(idx, start)); sb.append("<font bgcolor=\"FFB442\" color=\"black\">"); sb.append(s.substring(start, end)); sb.append("</font>"); idx = matcher.end(); } if(sb.length() > 0) { sb.append(idx < s.length() ? s.substring(idx, s.length()) : ""); s = sb.toString(); } return s; }
Example 6
Source File: RegexDemo.java From JavaCommon with Apache License 2.0 | 6 votes |
public static void match() { // 按指定模式在字符串查找 String line = "This order was placed for QT3000! OK?"; String pattern = "(\\D*)(\\d+)(.*)"; // 创建 Pattern 对象 Pattern r = Pattern.compile(pattern); // 现在创建 matcher 对象 Matcher m = r.matcher(line); if (m.groupCount() > 0) { System.out.println(m.groupCount()); for (int i = 0; i < m.groupCount(); i++) { System.out.println("Found value: " + m.group(i)); } } else { System.out.println("NO MATCH"); } }
Example 7
Source File: ReorgPolicyFactory.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private String computeNewName(String str, int resourceType) { int lastIndexOfDot= str.lastIndexOf('.'); String fileExtension= ""; //$NON-NLS-1$ String fileNameNoExtension= str; if (resourceType == IResource.FILE && lastIndexOfDot > 0) { fileExtension= str.substring(lastIndexOfDot); fileNameNoExtension= str.substring(0, lastIndexOfDot); } Pattern p= Pattern.compile("[0-9]+$"); //$NON-NLS-1$ Matcher m= p.matcher(fileNameNoExtension); if (m.find()) { // String ends with a number: increment it by 1 int newNumber= Integer.parseInt(m.group()) + 1; String numberStr= m.replaceFirst(Integer.toString(newNumber)); return numberStr + fileExtension; } else { return fileNameNoExtension + "2" + fileExtension; //$NON-NLS-1$ } }
Example 8
Source File: MaxWarns.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
void check(String out, int count) { System.err.println(out); Pattern warn = Pattern.compile("warning - @param argument \"i[0-9]+\" is not a parameter name"); Matcher m = warn.matcher(out); int n = 0; for (int start = 0; m.find(start); start = m.start() + 1) { n++; } if (n != count) error("unexpected number of warnings reported: " + n + "; expected: " + count); Pattern warnCount = Pattern.compile("(?ms).*^([0-9]+) warnings$.*"); m = warnCount.matcher(out); if (m.matches()) { n = Integer.parseInt(m.group(1)); if (n != count) error("unexpected number of warnings reported: " + n + "; expected: " + count); } else error("total count not found"); }
Example 9
Source File: Closure_107_CommandLineRunner_t.java From coming with MIT License | 5 votes |
/** * Split strings into tokens delimited by whitespace, but treat quoted * strings as single tokens. Non-whitespace characters adjacent to quoted * strings will be returned as part of the token. For example, the string * {@code "--js='/home/my project/app.js'"} would be returned as a single * token. * * @param lines strings to tokenize * @return a list of tokens */ private List<String> tokenizeKeepingQuotedStrings(List<String> lines) { List<String> tokens = Lists.newArrayList(); Pattern tokenPattern = Pattern.compile("(?:[^ \t\f\\x0B'\"]|(?:'[^']*'|\"[^\"]*\"))+"); for (String line : lines) { Matcher matcher = tokenPattern.matcher(line); while (matcher.find()) { tokens.add(matcher.group(0)); } } return tokens; }
Example 10
Source File: GrepFilter.java From Fairy with Apache License 2.0 | 5 votes |
private static String parseHtml(String rawContent, String grep) { Pattern pattern = Pattern.compile("(<(p)><font(\\s[^\\t\\n\\r\\>]+)?>([^<>])*" + grep + "([^<>])*<\\/p>)+?"); Matcher matcher = pattern.matcher(rawContent); StringBuilder stringBuilder = new StringBuilder(); while (matcher.find()) { stringBuilder.append(matcher.group()); } return stringBuilder.toString(); }
Example 11
Source File: BalancerManagerHtmlParser.java From jwala with Apache License 2.0 | 5 votes |
public Map<String, String> findBalancers(final String content) { LOGGER.info("Entering findBalancers:"); Map<String, String> balancers = new HashMap<>(); final String foundStringPrefix = "<h3>LoadBalancer Status for <a href=..balancer-manager\\?b="; final String foundStringPost = "nonce="; final String foundStringPostNonce = ">balancer"; final String matchStringBalancerNamePrefix = "?b="; final String matchPattern = foundStringPrefix + ".*." + foundStringPost + ".*"; String balancerName; String nonce; Pattern pattern = Pattern.compile(matchPattern); Matcher matcher = pattern.matcher(content); String matchString; while (matcher.find()) { matchString = matcher.group(); balancerName = matchString.substring(matchString.indexOf(matchStringBalancerNamePrefix) + matchStringBalancerNamePrefix.length(), matchString.indexOf("&")); nonce = matchString.substring(matchString.indexOf(foundStringPost) + foundStringPost.length(), matchString.indexOf(foundStringPostNonce) - 1); balancers.put(balancerName, nonce); } LOGGER.info("balancers.size: " + balancers.size()); for (Map.Entry entry : balancers.entrySet()) { LOGGER.info("balancerName: " + entry.getKey() + ", nonce: " + entry.getValue()); } return balancers; }
Example 12
Source File: ClientViewMapTest.java From p4ic4idea with Apache License 2.0 | 5 votes |
/** * Test exotic client view mappings. */ @Test public void testClientViewPattern() throws Exception { String[] viewMappings = { "\"//depot/122Bugs/job0592 53/files/chang es-2012.3.txt\" //job059253_client/files/abc123.txt", "\"//depot/122Bugs/job0592 53/files/\"chang es-2012.3\".txt\" //job059253_client/files/abc123.txt", "\"//depot/122 Bugs/job059253/files/changes-201 2.3.txt\" \"//job059253_client/fi les/ab c123.txt\"", "+//depot/122Bugs/job059253/files/\"main~40%2523$%2525^&%252A()_+changes\"-2012.3.txt \"//job059253_client/fi les/abc123.txt\"", "\"+//job059253_client/fi les/abc123.txt\"", "+//job059253_client/files/abc123.txt", "+//job059253_client/files/\"abc123.txt\"" }; List<String> list = new ArrayList<String>(); Pattern p = Pattern.compile(TOKEN_REGEX_PATTERN); for (String viewMapping : viewMappings) { Matcher m = p.matcher(viewMapping); while (m.find()) { if (m.groupCount() > 0) { if (isNotBlank(m.group(1))) { if (m.group(1).startsWith("\"")) { list.add(m.group(1).replaceAll("^\"|\"$", EMPTY)); } else { list.add(m.group(1)); } } } } } assertThat(list, notNullValue()); for(String item : list) { System.out.println(item); } }
Example 13
Source File: RegexUtil.java From Android-Architecture with Apache License 2.0 | 5 votes |
/** * 验证密码只能输入字母和数字的特殊字符,这个返回的是过滤之后的字符串 */ public static String checkPasWord(String pro) { try { // 只允许字母、数字和汉字 String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(pro); return m.replaceAll("").trim(); } catch (Exception e) { } return ""; }
Example 14
Source File: WavefrontObjectModelProvider.java From NOVA-Core with GNU Lesser General Public License v3.0 | 5 votes |
/** * Verifies that the given line from the model file is a valid for a given pattern * * @param line the line being validated * @param pattern the validator * @return true if the line is a valid for a given pattern, false otherwise */ private boolean isValid(String line, Pattern pattern) { if (globalMatcher != null) { globalMatcher.reset(); } globalMatcher = pattern.matcher(line); return globalMatcher.matches(); }
Example 15
Source File: Main.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
/** * Verify that a translate pattern is valid. */ private static void checkTranslatePattern(String s) throws ProblemException { // .prop=com.sun.tools.javac.smart.CompileProperties // .idl=com.sun.corba.CompileIdl // .g3=antlr.CompileGrammar,debug=true Pattern p = Pattern.compile( "\\.[a-zA-Z_]{1}[a-zA-Z0-9_]*=[a-z_]{1}[a-z0-9_]*(\\.[a-z_]{1}[a-z0-9_]*)*"+ "(\\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)(,.*)?"); Matcher m = p.matcher(s); if (!m.matches()) { throw new ProblemException("The string \""+s+"\" is not a proper translate pattern."); } }
Example 16
Source File: HitomiActivity.java From Hentoid with Apache License 2.0 | 5 votes |
/** * Specific implementation to get rid of Hitomi's ad js files * that have random names */ @Override protected boolean isUrlForbidden(@NonNull String url) { // 1- Process usual blacklist and cached dynamic blacklist if (super.isUrlForbidden(url)) return true; if (jsBlacklistCache.contains(url)) return true; // 2- Accept non-JS files if (!url.toLowerCase().endsWith(".js")) return false; // 3- Accept JS files defined in the whitelist for (Pattern p : whitelistUrlPattern) { Matcher matcher = p.matcher(url.toLowerCase()); if (matcher.find()) return false; } // 4- For the others (gray list), block them if they _contain_ keywords Timber.d(">> examining grey file %s", url); try { Response response = HttpHelper.getOnlineResource(url, null, getStartSite().canKnowHentoidAgent()); if (null == response.body()) throw new IOException("Empty body"); String jsBody = response.body().string().toLowerCase(); for (String s : blockedJsContents) if (jsBody.contains(s)) { jsBlacklistCache.add(url); return true; } } catch (IOException e) { Timber.e(e); } // Accept non-blocked grey JS files return false; }
Example 17
Source File: Word1Finder.java From KJump with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Nullable @Override public List<MarksCanvas.Mark> input(@NotNull Editor e, char c, @NotNull List<MarksCanvas.Mark> lastMarks) { switch (state) { case STATE_WAIT_SEARCH_CHAR: boolean ignoreCase = config.isSmartcase() && Character.isLowerCase(c); Pattern pattern = Pattern.compile((ignoreCase ? "(?i)" : "") + "\\b" + Pattern.quote("" + c)); Matcher m = pattern.matcher(s); List<Integer> offsets = new ArrayList<>(); while (m.find()) { offsets.add(m.start() + visibleRange.getStartOffset()); } offsets.sort((o1, o2) -> { int cOffset = e.getCaretModel().getOffset(); return Math.abs(o1 - cOffset) - Math.abs(o2 - cOffset); }); List<String> tags = KeyTagsGenerator.createTagsTree(offsets.size(), UserConfig.getDataBean().getCharacters()); List<MarksCanvas.Mark> res = new ArrayList<>(); for (int i = 0; i < offsets.size(); i++) { res.add(new MarksCanvas.Mark(tags.get(i), offsets.get(i))); } state = STATE_WAIT_KEY; return res; case STATE_WAIT_KEY: return FinderHelper.matchInputAndCreateMarks(c, lastMarks); default: throw new RuntimeException("Impossible."); } }
Example 18
Source File: Request4FreshNewsCommentList.java From JianDan with Apache License 2.0 | 4 votes |
@Override protected Response<ArrayList<Comment4FreshNews>> parseNetworkResponse(NetworkResponse response) { try { String resultStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); JSONObject resultObj = new JSONObject(resultStr); String status = resultObj.optString("status"); if (status.equals("ok")) { String commentsStr = resultObj.optJSONObject("post").optJSONArray("comments") .toString(); int id = resultObj.optJSONObject("post").optInt("id"); mCallBack.loadFinish(Integer.toString(id)); ArrayList<Comment4FreshNews> comment4FreshNewses = (ArrayList<Comment4FreshNews>) JSONParser.toObject(commentsStr, new TypeToken<ArrayList<Comment4FreshNews>>() { }.getType()); Pattern pattern = Pattern.compile("\\d{7}"); for (Comment4FreshNews comment4FreshNews : comment4FreshNewses) { Matcher matcher = pattern.matcher(comment4FreshNews.getContent()); boolean isHas7Num = matcher.find(); boolean isHasCommentStr = comment4FreshNews.getContent().contains("#comment-"); //有回复 if (isHas7Num && isHasCommentStr || comment4FreshNews.getParentId() != 0) { ArrayList<Comment4FreshNews> tempComments = new ArrayList<>(); int parentId = getParentId(comment4FreshNews.getContent()); comment4FreshNews.setParentId(parentId); getParenFreshNews(tempComments, comment4FreshNewses, parentId); Collections.reverse(tempComments); comment4FreshNews.setParentComments(tempComments); comment4FreshNews.setFloorNum(tempComments.size() + 1); comment4FreshNews.setContent(getContentWithParent(comment4FreshNews.getContent())); } else { comment4FreshNews.setContent(getContentOnlySelf(comment4FreshNews.getContent())); } } Logger.d("" + comment4FreshNewses); return Response.success(comment4FreshNewses, HttpHeaderParser .parseCacheHeaders(response)); } else { return Response.error(new ParseError(new Exception("request failed"))); } } catch (Exception e) { e.printStackTrace(); return Response.error(new ParseError(e)); } }
Example 19
Source File: AggregateActivityInstancesStep.java From bpmn.ai with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public Dataset<Row> runPreprocessingStep(Dataset<Row> dataset, Map<String, Object> parameters, SparkRunnerConfig config) { //apply first and processState aggregator Map<String, String> aggregationMap = new HashMap<>(); for(String column : dataset.columns()) { if(column.equals(BpmnaiVariables.VAR_PROCESS_INSTANCE_ID)) { continue; } else if(column.equals(BpmnaiVariables.VAR_DURATION) || column.endsWith("_rev")) { aggregationMap.put(column, "max"); } else if(column.equals(BpmnaiVariables.VAR_STATE)) { aggregationMap.put(column, "ProcessState"); } else if(column.equals(BpmnaiVariables.VAR_ACT_INST_ID)) { //ignore it, as we aggregate by it continue; } else { aggregationMap.put(column, "AllButEmptyString"); } } //first aggregation //activity level, take only processInstance and activityInstance rows dataset = dataset .filter(dataset.col(BpmnaiVariables.VAR_DATA_SOURCE).notEqual(BpmnaiVariables.EVENT_PROCESS_INSTANCE)) .groupBy(BpmnaiVariables.VAR_PROCESS_INSTANCE_ID, BpmnaiVariables.VAR_ACT_INST_ID) .agg(aggregationMap); //rename back columns after aggregation String pattern = "(max|allbutemptystring|processstate)\\((.+)\\)"; Pattern r = Pattern.compile(pattern); for(String columnName : dataset.columns()) { Matcher m = r.matcher(columnName); if(m.find()) { String newColumnName = m.group(2); dataset = dataset.withColumnRenamed(columnName, newColumnName); } } //in case we add the CSV we have a name column in the first dataset of the join so we call drop again to make sure it is gone dataset = dataset.drop(BpmnaiVariables.VAR_PROCESS_INSTANCE_VARIABLE_NAME); dataset = dataset.drop(BpmnaiVariables.VAR_DATA_SOURCE); dataset = dataset.sort(BpmnaiVariables.VAR_START_TIME); dataset.cache(); BpmnaiLogger.getInstance().writeInfo("Found " + dataset.count() + " activity instances."); if(config.isWriteStepResultsIntoFile()) { BpmnaiUtils.getInstance().writeDatasetToCSV(dataset, "agg_of_activity_instances", config); } //return preprocessed data return dataset; }
Example 20
Source File: StringUtil.java From ShoppingCartActivity with Apache License 2.0 | 4 votes |
private static boolean match(String regex, String str) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); return matcher.matches(); }