Java Code Examples for java.util.regex.Pattern#compile()

The following examples show how to use java.util.regex.Pattern#compile() . 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 Project: 4pdaClient-plus   File: ThemeFragment.java    License: Apache License 2.0 6 votes vote down vote up
private void showImage(String url) {
    Pattern tPattern = Pattern.compile("(post\\/\\d*?\\/[\\s\\S]*?\\.(?:png|jpg|jpeg|gif))");
    Matcher target = tPattern.matcher(url);
    Matcher temp;
    String id;
    if (target.find()) {
        id = target.group(1);
        for (ArrayList<String> list : imageAttaches) {
            for (int i = 0; i < list.size(); i++) {
                temp = tPattern.matcher(list.get(i));
                if (temp.find()) {
                    if (temp.group(1).equals(id)) {
                        ImgViewer.startActivity(getContext(), list, i);
                        return;
                    }
                }
            }
        }
        ImgViewer.startActivity(getContext(), url);
    }

}
 
Example 2
private String getLatestSnapshot(final String snapshotNameMask, final Map<String, VirtualMachineSnapshotTree> snapshotList) {
  if (snapshotNameMask == null)
    return null;
  if (!snapshotNameMask.contains("*") && !snapshotNameMask.contains("?")) {
    return snapshotList.containsKey(snapshotNameMask) ? snapshotNameMask : null;
  }
  Date latestTime = new Date(0);
  String latestSnapshotName = null;
  for (Map.Entry<String, VirtualMachineSnapshotTree> entry : snapshotList.entrySet()) {
    final String snapshotNameMaskRegex = StringUtil.convertWildcardToRegexp(snapshotNameMask);
    final Pattern pattern = Pattern.compile(snapshotNameMaskRegex);
    if (pattern.matcher(entry.getKey()).matches()) {
      final Date snapshotTime = entry.getValue().getCreateTime().getTime();
      if (latestTime.before(snapshotTime)) {
        latestTime = snapshotTime;
        latestSnapshotName = entry.getKey();
      }
    }
  }
  return latestSnapshotName;
}
 
Example 3
String checkSensitivity(String site, String resource, Set<String> childSensitiveTypes) {
    Map<String, Map<String, String>> maps = getAllSensitivities();
    String sensitiveType = null;
    if (maps != null && maps.get(site) != null) {
        Map<String, String> map = maps.get(site);
        for (String r : map.keySet()) {
            Pattern pattern = Pattern.compile("^" + resource);
            boolean isMatched = Pattern.matches(r, resource);
            if (isMatched) {
                sensitiveType = map.get(r);
            }
            else if (pattern.matcher(r).find()){
                childSensitiveTypes.add(map.get(r));
            }
        }
    }
    return sensitiveType;
}
 
Example 4
Source Project: nifi   File: TestAbstractListProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public long removeByPattern(String regex) throws IOException {
    final List<Object> removedRecords = new ArrayList<>();
    Pattern p = Pattern.compile(regex);
    for (Object key : stored.keySet()) {
        // Key must be backed by something that can be converted into a String
        Matcher m = p.matcher(key.toString());
        if (m.matches()) {
            removedRecords.add(stored.get(key));
        }
    }
    final long numRemoved = removedRecords.size();
    removedRecords.forEach(stored::remove);
    return numRemoved;
}
 
Example 5
private static String separateCompleteVersion(String completeVersion, String part) {
	logger.debug("IN");
	String toReturn = "";
	// Find all digits separated by dot (.) + optional i.e. [7.0.0-SNAPSHOT]
	Pattern regexPattern = Pattern.compile("([\\d]+)\\.([\\d]+)\\.([\\d]+)(-(.+))?");
	Matcher matcher = regexPattern.matcher(completeVersion);
	if (matcher.find()) {
		switch (part) {
		case "MAJOR":
			toReturn = matcher.group(1);
			break;
		case "MINOR":
			toReturn = matcher.group(2);
			break;
		case "PATCH":
			toReturn = matcher.group(3);
			break;
		case "OPTIONAL":
			toReturn = matcher.group(5);
			break;
		default:
			toReturn = completeVersion;
			break;
		}
	}
	logger.debug("OUT");
	return toReturn;
}
 
Example 6
Source Project: DataVec   File: Configuration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the value of the <code>name</code> property as a <ocde>Pattern</code>.
 * If no such property is specified, or if the specified value is not a valid
 * <code>Pattern</code>, then <code>DefaultValue</code> is returned.
 *
 * @param name property name
 * @param defaultValue default value
 * @return property value as a compiled Pattern, or defaultValue
 */
public Pattern getPattern(String name, Pattern defaultValue) {
    String valString = get(name);
    if (null == valString || "".equals(valString)) {
        return defaultValue;
    }
    try {
        return Pattern.compile(valString);
    } catch (PatternSyntaxException pse) {
        LOG.warn("Regular expression '" + valString + "' for property '" + name + "' not valid. Using default",
                        pse);
        return defaultValue;
    }
}
 
Example 7
private static void showLinks(String content) {
   Pattern pattern = Pattern.compile("(?i)HREF\\s*=\\s*\"(.*?)\"");
   Matcher matcher = pattern.matcher(content);
   while (matcher.find()) {
      System.out.println(matcher.group(1));
   }
}
 
Example 8
Source Project: roboconf-platform   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Expands a template, replacing each {{ param }} by the corresponding value.
 * <p>
 * Eg. "My name is {{ name }}" will result in "My name is Bond", provided that "params" contains "name=Bond".
 * </p>
 *
 * @param s the template to expand
 * @param params the parameters to be expanded in the template
 * @return the expanded template
 */
public static String expandTemplate(String s, Properties params) {

	String result;
	if( params == null || params.size() < 1 ) {
		result = s;

	} else {
		StringBuffer sb = new StringBuffer();
		Pattern pattern = Pattern.compile( "\\{\\{\\s*\\S+\\s*\\}\\}" );
		Matcher m = pattern.matcher( s );

		while( m.find()) {
			String raw = m.group();
			String varName = m.group().replace('{', ' ').replace('}', ' ').trim();
			String val = params.getProperty(varName);
			val = (val == null ? raw : val.trim());

			m.appendReplacement(sb, val);
		}

		m.appendTail( sb );
		result = sb.toString();
	}

	return result;
}
 
Example 9
Source Project: 4pdaClient-plus   File: ThemeFragment.java    License: Apache License 2.0 5 votes vote down vote up
private void setScrollElement() {
    m_ScrollElement = null;

    String url = getLastUrl();
    if (url != null) {
        Pattern p = Pattern.compile("#(\\w+\\d+)");
        Matcher m = p.matcher(url);
        if (m.find()) {
            m_ScrollElement = m.group(1);
        }
    }
}
 
Example 10
Source Project: aliada-tool   File: Cache.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Pattern getEndPattern(final String regex) {
	Pattern p = endPatterns.get(regex);
	if (p == null) {
		p = Pattern.compile("</(" + regex + ")>");
		endPatterns.put(regex, p);
	}
	
	return p;
}
 
Example 11
/**
 * 判断是否为数字
 *
 * @param str
 * @return
 */
public static boolean isNumeric(String str) {
    Pattern pattern = Pattern.compile("[0-9]*");
    Matcher isNum = pattern.matcher(str);
    if (!isNum.matches()) {
        return false;
    }
    return true;
}
 
Example 12
@NotNull
private static String removeParentheses(@NotNull String text) {
    final Pattern pattern = Pattern.compile(".*(?=(?:\\([0-9]+\\))$)");
    final Matcher matcher = pattern.matcher(text);
    if (matcher.find()) {
        return matcher.group(0).trim();
    } else {
        return text;
    }
}
 
Example 13
Source Project: graphouse   File: MetricValidator.java    License: Apache License 2.0 5 votes vote down vote up
public MetricValidator(String metricRegexp, int minMetricLength, int maxMetricLength, int minDots, int maxDots) {
    this.minMetricLength = minMetricLength;
    this.maxMetricLength = maxMetricLength;
    this.minDots = minDots;
    this.maxDots = maxDots;
    metricPattern = Pattern.compile(metricRegexp);
}
 
Example 14
Source Project: android-tv-launcher   File: Tools.java    License: MIT License 5 votes vote down vote up
/**
 * 
 * @param pwd
 * @return
 * 
 */
public static boolean isCorrectUserPwd(String pwd) {
	Pattern p = Pattern.compile("\\w{6,18}");
	Matcher m = p.matcher(pwd);
	System.out.println(m.matches() + "-pwd-");
	return m.matches();
}
 
Example 15
public static String generateDocumentTypeNumber(long groupId, long companyId, long documentTypeId)
			throws ParseException {
		DocumentType documentType = DocumentTypeLocalServiceUtil.fetchDocumentType(documentTypeId);
		String seriNumberPattern = null;		
		
		String documentTypeNumber = StringPool.BLANK;

		if (documentType != null) {
			seriNumberPattern = documentType.getCodePattern();
			String codePattern = "\\{(n+|N+)\\}";
			String dayPattern = "\\{(d{2}|D{2})\\}";
			String monthPattern = "\\{(m{2}|M{2})\\}";
			String yearPattern = "\\{(y+|Y+)\\}";
			String dynamicVariablePattern = "\\{\\$(.*?)\\}";
			String datetimePattern = "\\{([D|d]{2}[-\\/]{1}[M|m]{2}[-|\\/]{1}[Y|y]{4})\\}";
			String[] patterns = new String[] { codePattern, dayPattern, monthPattern, yearPattern,
					dynamicVariablePattern, datetimePattern };

			Date now = new Date();

			String day = String.valueOf(DateTimeUtils.getDayFromDate(now));
			String month = String.valueOf(DateTimeUtils.getMonthFromDate(now));
			String year = String.valueOf(DateTimeUtils.getYearFromDate(now));

			for (String pattern : patterns) {
				Pattern r = Pattern.compile(pattern);

				Matcher m = r.matcher(seriNumberPattern);

				while (m.find()) {
					String tmp = m.group(1);

					if (r.toString().equals(codePattern)) {
						String number = countByInit(pattern, 0L);

						tmp = tmp.replaceAll(tmp.charAt(0) + StringPool.BLANK, String.valueOf(0));
						if (number.length() < tmp.length()) {
							number = tmp.substring(0, tmp.length() - number.length()).concat(number);
						}
						seriNumberPattern = seriNumberPattern.replace(m.group(0), number);
					} else if (r.toString().equals(datetimePattern)) {
//						System.out.println(tmp);

						seriNumberPattern = seriNumberPattern.replace(m.group(0), "OK");

					} else if (r.toString().equals(dayPattern)) {

						tmp = tmp.replaceAll(tmp.charAt(0) + StringPool.BLANK, String.valueOf(0));

						if (day.length() < tmp.length()) {
							day = tmp.substring(0, tmp.length() - day.length()).concat(day);
						} else if (day.length() > tmp.length()) {
							day = day.substring(day.length() - tmp.length(), day.length());
						}

						seriNumberPattern = seriNumberPattern.replace(m.group(0), day);

					} else if (r.toString().equals(monthPattern)) {

						tmp = tmp.replaceAll(tmp.charAt(0) + StringPool.BLANK, String.valueOf(0));

						if (month.length() < tmp.length()) {
							month = tmp.substring(0, tmp.length() - month.length()).concat(month);
						} else if (month.length() > tmp.length()) {
							month = month.substring(month.length() - tmp.length(), month.length());
						}

						seriNumberPattern = seriNumberPattern.replace(m.group(0), month);

					} else if (r.toString().equals(yearPattern)) {

						tmp = tmp.replaceAll(tmp.charAt(0) + StringPool.BLANK, String.valueOf(0));

						if (year.length() < tmp.length()) {
							year = tmp.substring(0, tmp.length() - year.length()).concat(year);
						} else if (year.length() > tmp.length()) {
							year = year.substring(year.length() - tmp.length(), year.length());
						}

						seriNumberPattern = seriNumberPattern.replace(m.group(0), year);

					}
					m = r.matcher(seriNumberPattern);
				}
			}

			documentTypeNumber = seriNumberPattern;
		}
		return documentTypeNumber;
	}
 
Example 16
Source Project: suro   File: RoutingKeyFilter.java    License: Apache License 2.0 4 votes vote down vote up
@JsonCreator
public RoutingKeyFilter(@JsonProperty(JSON_PROPERTY_REGEX) String regex) {
    filterPattern = Pattern.compile(regex);
}
 
Example 17
Source Project: openjdk-8   File: IPv6.java    License: GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        String[][] kdcs = {
                {"simple.host", null},  // These are legal settings
                {"simple.host", ""},
                {"simple.host", "8080"},
                {"0.0.0.1", null},
                {"0.0.0.1", ""},
                {"0.0.0.1", "8080"},
                {"1::1", null},
                {"[1::1]", null},
                {"[1::1]", ""},
                {"[1::1]", "8080"},
                {"[1::1", null},        // Two illegal settings
                {"[1::1]abc", null},
        };
        // Prepares a krb5.conf with every kind of KDC settings
        PrintStream out = new PrintStream(new FileOutputStream("ipv6.conf"));
        out.println("[libdefaults]");
        out.println("default_realm = V6");
        out.println("kdc_timeout = 1");
        out.println("[realms]");
        out.println("V6 = {");
        for (String[] hp: kdcs) {
            if (hp[1] != null) out.println("    kdc = "+hp[0]+":"+hp[1]);
            else out.println("    kdc = " + hp[0]);
        }
        out.println("}");
        out.close();

        System.setProperty("sun.security.krb5.debug", "true");
        System.setProperty("java.security.krb5.conf", "ipv6.conf");

        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        PrintStream po = new PrintStream(bo);
        PrintStream oldout = System.out;
        System.setOut(po);

        try {
            Subject subject = new Subject();
            Krb5LoginModule krb5 = new Krb5LoginModule();
            Map<String, String> map = new HashMap<>();
            Map<String, Object> shared = new HashMap<>();

            map.put("debug", "true");
            map.put("doNotPrompt", "true");
            map.put("useTicketCache", "false");
            map.put("useFirstPass", "true");
            shared.put("javax.security.auth.login.name", "any");
            shared.put("javax.security.auth.login.password", "any".toCharArray());
            krb5.initialize(subject, null, shared, map);
            krb5.login();
        } catch (Exception e) {
            // Ignore
        }

        po.flush();

        System.setOut(oldout);
        BufferedReader br = new BufferedReader(new StringReader(
                new String(bo.toByteArray())));
        int cc = 0;
        Pattern r = Pattern.compile(".*KrbKdcReq send: kdc=(.*) UDP:(\\d+),.*");
        String line;
        while ((line = br.readLine()) != null) {
            Matcher m = r.matcher(line.subSequence(0, line.length()));
            if (m.matches()) {
                System.out.println("------------------");
                System.out.println(line);
                String h = m.group(1), p = m.group(2);
                String eh = kdcs[cc][0], ep = kdcs[cc][1];
                if (eh.charAt(0) == '[') {
                    eh = eh.substring(1, eh.length()-1);
                }
                System.out.println("Expected: " + eh + " : " + ep);
                System.out.println("Actual: " + h + " : " + p);
                if (!eh.equals(h) ||
                        (ep == null || ep.length() == 0) && !p.equals("88") ||
                        (ep != null && ep.length() > 0) && !p.equals(ep)) {
                    throw new Exception("Mismatch");
                }
                cc++;
            }
        }
        if (cc != kdcs.length - 2) {    // 2 illegal settings at the end
            throw new Exception("Not traversed");
        }
    }
 
Example 18
Source Project: stratio-cassandra   File: OptionSimple.java    License: Apache License 2.0 4 votes vote down vote up
public OptionSimple(String prefix, String valuePattern, String defaultValue, String description, boolean required)
{
    this(prefix, Pattern.compile(Pattern.quote(prefix), Pattern.CASE_INSENSITIVE),
         Pattern.compile(valuePattern, Pattern.CASE_INSENSITIVE), defaultValue, description, required);
}
 
Example 19
Source Project: TrMenu   File: Mat.java    License: MIT License 4 votes vote down vote up
Option(String pattern) {
    this.pattern = Pattern.compile("(?i)" + pattern);
}
 
Example 20
Source Project: roncoo-pay   File: ValidateUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 是否为合法MAC地址,验证十六进制格式
 * 
 * @param mac
 * @return
 */
public static boolean isMac(String mac) {
	Pattern pattern = Pattern.compile("^([0-9a-fA-F]{2})(([\\s:-][0-9a-fA-F]{2}){5})$");
	return pattern.matcher(mac).matches();
}