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

The following are Jave code examples for showing how to use compile() of the java.util.regex.Pattern class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: dubbo2   File: ParseUtils.java   View Source Code Vote up 6 votes
/**
 * 替换url中参数的值。
 */
public static String replaceParameter(String query, String key, String value) {
    if (query == null || query.length() == 0) {
        return key + "=" + value;
    }
    if (query.indexOf(key + "=") == -1) {
    	return query + "&" + key + "=" + value;
    }
    Pattern pattern = REPLACE_PARAMETER_PATTERNS.get(key);
    if (pattern == null) {
    	pattern = Pattern.compile(key.replaceAll("([^(_0-9A-Za-z)])", "\\\\$0") + "=[^&]+");
    }
    Matcher matcher = pattern.matcher(query);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(sb, (key + "=" + value).replace("$", "\\$"));
    }
    matcher.appendTail(sb);
    return sb.toString();
}
 
Example 2
Project: okwallet   File: BtcFormat.java   View Source Code Vote up 6 votes
ScaleMatcher[] denomMatchers() {
    ScaleMatcher[] result = denoms;
    if (result == null) { synchronized(this) {
        result = denoms;
        if (result == null) {
            if (! coinSymbol().matches(ci)) ci = ci.replaceFirst("\\(", "(" + coinSymbol() + "|");
            if (! coinCode().matches(ci))  {
                ci = ci.replaceFirst("\\)", "|" + coinCode() + ")");
            }
            coinPattern = Pattern.compile(ci + "?");
            result = denoms = new ScaleMatcher[]{
                new ScaleMatcher(Pattern.compile("¢" + ci + "?|c" + ci), 2), // centi 
                new ScaleMatcher(Pattern.compile("₥" + ci + "?|m" + ci), MILLICOIN_SCALE),
                new ScaleMatcher(Pattern.compile("([µu]" + ci + ")"),    MICROCOIN_SCALE),
                new ScaleMatcher(Pattern.compile("(da" + ci + ")"),     -1), // deka
                new ScaleMatcher(Pattern.compile("(h" + ci + ")"),      -2), // hekto
                new ScaleMatcher(Pattern.compile("(k" + ci + ")"),      -3), // kilo
                new ScaleMatcher(Pattern.compile("(M" + ci + ")"),      -6)  // mega
            };
        }
    }}
    return result;
}
 
Example 3
Project: openjdk-jdk10   File: T8038414.java   View Source Code Vote up 6 votes
/**
 * Returns a list which contains comments of the string entry in the constant pool
 * and the appropriate UTF-8 value.
 *
 * @return a list
 */
private List<String> extractEscapedComments(String output) {
    List<String> result = new ArrayList<>();
    Pattern stringPattern = Pattern.compile(" +#\\d+ = String +#(\\d+) +// +(.*)");
    int index = -1;
    List<String> cp = extractConstantPool(output);
    for (String c : cp) {
        Matcher matcher = stringPattern.matcher(c);
        if (matcher.matches()) {
            index = Integer.parseInt(matcher.group(1)) - 1;
            result.add(matcher.group(2));
            // only one String entry
            break;
        }
    }
    check(index == -1, "Escaped string is not found in constant pool");
    result.add(cp.get(index).replaceAll(".* +", "")); // remove #16 = Utf8
    return result;
}
 
Example 4
Project: lazycat   File: ExpressionParseTree.java   View Source Code Vote up 6 votes
protected int compareBranches() {
	String val1 = ((StringNode) left).getValue();
	String val2 = ((StringNode) right).getValue();

	int val2Len = val2.length();
	if (val2Len > 1 && val2.charAt(0) == '/' && val2.charAt(val2Len - 1) == '/') {
		// Treat as a regular expression
		String expr = val2.substring(1, val2Len - 1);
		try {
			Pattern pattern = Pattern.compile(expr);
			// Regular expressions will only ever be used with EqualNode
			// so return zero for equal and non-zero for not equal
			if (pattern.matcher(val1).find()) {
				return 0;
			} else {
				return -1;
			}
		} catch (PatternSyntaxException pse) {
			ssiMediator.log("Invalid expression: " + expr, pse);
			return 0;
		}
	}
	return val1.compareTo(val2);
}
 
Example 5
Project: personium-core   File: AbstractUserDataTest.java   View Source Code Vote up 6 votes
/**
 * UserDataの名前空間を取得する.
 * @param entityType エンティティタイプ名
 * @param col コレクション名
 * @return UserDataの名前空間
 */
protected String getNameSpace(String entityType, String col) {
    // NameSpace取得のためにメタデータを取得する
    TResponse res = Http.request("box/$metadata-$metadata-get.txt")
            .with("path", "\\$metadata")
            .with("col", col)
            .with("accept", "application/xml")
            .with("token", PersoniumUnitConfig.getMasterToken())
            .returns()
            .statusCode(HttpStatus.SC_OK)
            .debug();
    Pattern pattern = Pattern.compile("Namespace=\"([^\"]+)\">");
    Matcher matcher = pattern.matcher(res.getBody());
    matcher.find();
    return matcher.group(1) + "." + entityType;
}
 
Example 6
Project: SER316-Ingolstadt   File: Finder.java   View Source Code Vote up 5 votes
/**
 * Constructor for Finder.
 */
public Finder(
    HTMLEditor theEditor,
    String find,
    boolean wholeWord,
    boolean matchCase,
    boolean regexp,
    String replace) {
    super();
    editor = theEditor;
    dispText = find;
    int flags = Pattern.DOTALL;
    if (!matchCase)
        flags = flags + Pattern.CASE_INSENSITIVE + Pattern.UNICODE_CASE;
    _find = find;
    if (!regexp)
        _find = "\\Q" + _find + "\\E";
    if (wholeWord)
        _find = "[\\s\\p{Punct}]" + _find + "[\\s\\p{Punct}]";
    try {
        pattern = Pattern.compile(_find, flags);
    }
    catch (Exception ex) {
        ex.printStackTrace();
        pattern = null;
    }
    _replace = replace;
}
 
Example 7
Project: act-platform   File: PropertiesFileParser.java   View Source Code Vote up 5 votes
private Map<Long, Set<String>> parseSubjectPermissions(Properties properties, long subjectID) {
  Map<Long, Set<String>> permissions = new HashMap<>();

  Pattern permissionPattern = Pattern.compile(SUBJECT_PERMISSION_KEY.replace("{id}", String.valueOf(subjectID)));
  for (String key : properties.stringPropertyNames()) {
    Matcher matcher = permissionPattern.matcher(key);
    if (!matcher.matches()) continue;
    // Extract organizationID from key and parse function (group) names.
    permissions.put(Long.parseUnsignedLong(matcher.group(1)), parseStringMembers(properties, key));
  }

  return permissions;
}
 
Example 8
Project: springbootWeb   File: ValidateRegexpValidator.java   View Source Code Vote up 5 votes
@Override
public boolean isValid(final Object value, ConstraintValidatorContext context) {
    if (value == null || "".equals(value)) {
        return true;
    } else if (!StringUtil.isEmpty(validateRegexp.regexp())) {
        Pattern pattern = Pattern.compile(validateRegexp.regexp());
        Matcher matcher = pattern.matcher(value.toString().replaceAll("/", ""));
        return matcher.matches();
    }
    return false;
}
 
Example 9
Project: SoftUni   File: p02_LetterExpression.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws IOException{
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    StringBuilder string = new StringBuilder();
    string.append(reader.readLine());
    String regex = "(?<num>(\\d+)|^)(?<op>[^0-9]+|$)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(string);
    Double result = 0d;
    boolean plus = true;
    while(matcher.find()){
        /*System.out.println("full match " + matcher.group(0));
        System.out.println("num is " + matcher.group("num"));
        System.out.println("operator is " + (matcher.group("op").length() % 2 == 0 ? "+" : "-"));*/
        Double num = 0d;
        if(!matcher.group("num").isEmpty()){
            num = Double.parseDouble(matcher.group("num"));
        }
        if(plus){
            result += num;
        } else {
            result -= num;
        }
        plus = matcher.group("op").length() % 2 == 0;
    }
    DecimalFormat myFormat = new DecimalFormat("0.#######");
    System.out.println(myFormat.format(result));
}
 
Example 10
Project: scorekeeperfrontend   File: ClassData.java   View Source Code Vote up 5 votes
private Set<Index> globItem(String item, Set<Index> full)
{
    Set<Index> ret = new HashSet<Index>();
    Pattern glob = Pattern.compile('^' + item.trim().replace("*", ".*") + '$');
    for (Index idx : full) {
        if (glob.matcher(idx.getCode()).find())
            ret.add(idx);
    }
    return ret;
}
 
Example 11
Project: exportExcel   File: RegularUtils.java   View Source Code Vote up 5 votes
/**
 * <p>正则提取匹配到的内容</p>
 * <p>例如:</p>
 * </br>
 * author : Crab2Died</br>
 * date   : 2017年06月02日  15:49:51</br>
 *
 * @param pattern 匹配目标内容
 * @param reg     正则表达式
 * @param group   提取内容索引
 * @return 提取内容集合
 * @throws {@link RuntimeException}
 */
static
public List<String> match(String pattern, String reg, int group)
        throws RuntimeException {

    List<String> matchGroups = new ArrayList<>();
    Pattern compile = Pattern.compile(reg);
    Matcher matcher = compile.matcher(pattern);
    if (group > matcher.groupCount() || group < 0)
        throw new RuntimeException("Illegal match group :" + group);
    while (matcher.find()) {
        matchGroups.add(matcher.group(group));
    }
    return matchGroups;
}
 
Example 12
Project: OSchina_resources_android   File: HTMLUtil.java   View Source Code Vote up 5 votes
/**
 * 基本功能:过滤指定标签
 *
 * @param str
 * @param tag 指定标签
 * @return String
 */
public static String fiterHtmlTag(String str, String tag) {
    String regxp = "<\\s*" + tag + "\\s+([^>]*)\\s*>";
    Pattern pattern = Pattern.compile(regxp);
    Matcher matcher = pattern.matcher(str);
    StringBuffer sb = new StringBuffer();
    boolean result1 = matcher.find();
    while (result1) {
        matcher.appendReplacement(sb, "");
        result1 = matcher.find();
    }
    matcher.appendTail(sb);
    return sb.toString();
}
 
Example 13
Project: dds-examples   File: ConfigurationTest.java   View Source Code Vote up 5 votes
@Test(timeout = 4000)
public void test26() throws Throwable {
  Configuration configuration0 = new Configuration();
  Pattern pattern0 = Pattern.compile("7e:P");
  configuration0.setAllowPartitionNameFilter(pattern0);
  Pattern pattern1 = configuration0.getAllowPartitionNameFilter();
  assertEquals(0, pattern1.flags());
}
 
Example 14
Project: openjdk-jdk10   File: MethodFilter.java   View Source Code Vote up 5 votes
private static Pattern createClassGlobPattern(String pattern) {
    if (pattern.length() == 0) {
        return null;
    } else if (pattern.contains(".")) {
        return Pattern.compile(createGlobString(pattern));
    } else {
        return Pattern.compile("([^\\.\\$]*[\\.\\$])*" + createGlobString(pattern));
    }
}
 
Example 15
Project: QueryBuilder   File: NotEndsWithRuleParser.java   View Source Code Vote up 4 votes
public BasicDBObject parse(IRule rule, JsonRuleParser parser) {
    BasicDBObject operate = new BasicDBObject("$regex", Pattern.compile("(?<!" + rule.getValue() + ")$"));
    return new BasicDBObject(rule.getField(), operate);
}
 
Example 16
Project: keybiner   File: Authorizer.java   View Source Code Vote up 4 votes
/**
 *
 * @param resourceId
 * @param subResourceId
 * @param entitlements
 * @param ABF
 * @param authzAmount
 * @return
 */
public static boolean isAuthorized(String resourceId, String subResourceId, Entitlements entitlements, String ABF, int authzAmount)  {
    try {
        if (entitlements == null) {
            throw new Exception("Invalid Entitlements");
        }
        Pattern ABFPattern = null;
        String regexABF = ABF;
        if (authzAmount > 0)
            regexABF = regexABF +"\\$\\d*\\$";

        ABFPattern = Pattern.compile(regexABF);

        Subject subject = entitlements.getSubject();
        if (subject != null && subject.getABFs() != null && patternMatch(ABFPattern, subject.getABFs(), authzAmount ) )
            return true;


        List<Resource> resources = entitlements.getResources();

        if (resourceId!= null && resources != null)   {
            for (Iterator<Resource> resource = resources.iterator(); resource.hasNext(); ) {
                Resource ac = resource.next();
                if (! resourceId.equals(ac.getId())) continue;
                if (ac.getABFs()!= null && patternMatch(ABFPattern,ac.getABFs(), authzAmount ))  {
                    return true;
                }
                List<Resource> subResources = ac.getSubResources();
                if (subResourceId != null && subResources != null) {
                    for (Iterator<Resource> j = subResources.iterator(); j.hasNext(); ) {
                        Resource subResource = j.next();
                        if (!subResourceId.equals(subResource.getId())) continue;
                        if (subResource.getABFs() != null && patternMatch(ABFPattern,subResource.getABFs(), authzAmount ))
                            return true;
                    }
                }
            }
        }
    } catch (Exception ex)  {
        LOG.error(ex.getMessage(), ex);

    }
    return false;
}
 
Example 17
Project: elasticsearch_my   File: PatternAnalyzerTests.java   View Source Code Vote up 4 votes
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
  Analyzer a = new PatternAnalyzer(Pattern.compile(","), true, StopAnalyzer.ENGLISH_STOP_WORDS_SET);
  checkRandomData(random(), a, 10000*RANDOM_MULTIPLIER);
}
 
Example 18
Project: GCSApp   File: CheckUtil.java   View Source Code Vote up 4 votes
public static boolean IsEmail(String email) {
	Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
	Matcher matcher = pattern.matcher(email);
	return matcher.matches();
}
 
Example 19
Project: Panako   File: FileUtils.java   View Source Code Vote up 3 votes
/**
 * <p>
 * Return a list of files in directory that satisfy pattern. Pattern should
 * be a valid regular expression not a 'unix glob pattern' so in stead of
 * <code>*.wav</code> you could use <code>.*\.wav</code>
 * </p>
 * <p>
 * E.g. in a directory <code>home</code> with the files
 * <code>com.test.txt</code>, <code>blaat.wav</code> and <code>foobar.wav</code>
 * the pattern <code>.*\.wav</code> matches <code>blaat.wav</code> and
 * <code>foobar.wav</code>
 * </p>
 * 
 * @param directory
 *            A readable directory.
 * @param pattern
 *            A valid regular expression.
 * @param recursive
 *            A boolean defining if directories should be traversed
 *            recursively.
 * @return a list of filenames matching the pattern for directory.
 * @exception Error
 *                an error is thrown if the directory is not ... a
 *                directory.
 * @exception java.util.regex.PatternSyntaxException
 *                Unchecked exception thrown to indicate a syntax error in a
 *                regular-expression pattern.
 */
public static List<String> glob(final String directory, final String pattern, final boolean recursive) {
	final List<String> matchingFiles = new ArrayList<String>();
	final Pattern p = Pattern.compile(pattern);
	final File dir = new File(new File(directory).getAbsolutePath());
	glob(dir, p, recursive, matchingFiles);
	// sort alphabetically
	Collections.sort(matchingFiles);
	return matchingFiles;
}
 
Example 20
Project: javadoc2swagger   File: ResponseParser.java   View Source Code Vote up 3 votes
/**
 * Searches for responses in a String.
 * 
 * @param section
 *            javadoc section
 * @param imports
 *            imports of a java file
 * @param fileName
 *            java file name
 * @param packageName
 *            package name of current java file
 * @return List of {@link Resource}
 * @throws ParserException
 *             Error while the parsing process
 */
public List<Response> findResponsesInJavadocSection(String section, List<String> imports, String fileName,
        String packageName) throws ParserException {
    List<Response> responses = new ArrayList<>();
    String regex = "@responseCode [0-9]{1,3}([\\s]|@responseSchema \\{@link \\w+\\}|@responseType [a-zA-Z]+|@responseMessage [^@]+)*";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(section);
    while (matcher.find()) {
        String responseSection = section.substring(matcher.start(), matcher.end());
        responses.add(generateResponseFromSection(responseSection, imports, fileName, packageName));
    }
    return responses;
}