Java Code Examples for java.util.regex.Pattern

The following are top voted examples for showing how to use java.util.regex.Pattern. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: letv   File: ab.java   View source code 6 votes vote down vote up
public static int a(Set<String> set) {
    if (set == null || set.isEmpty()) {
        return 0;
    }
    if (set.size() > 100) {
        return d.g;
    }
    for (String str : set) {
        if (str == null) {
            return d.e;
        }
        if (str.getBytes().length > 40) {
            return d.f;
        }
        if (!Pattern.compile(z[1]).matcher(str).matches()) {
            return d.e;
        }
    }
    return 0;
}
 
Example 2
Project: fresco_floodlight   File: ActionUtils.java   View source code 6 votes vote down vote up
/**
 * Parse set_vlan_pcp actions.
 * The key and delimiter for the action should be omitted, and only the
 * data should be presented to this decoder. Data with a leading 0x is permitted.
 * 
 * @param actionToDecode; The action as a string to decode
 * @param version; The OF version to create the action for
 * @param log
 * @return
 */
private static OFActionSetVlanPcp decode_set_vlan_priority(String actionToDecode, OFVersion version, Logger log) {
	Matcher n = Pattern.compile("((?:0x)?\\d+)").matcher(actionToDecode); 
	if (n.matches()) {            
		if (n.group(1) != null) {
			try {
				VlanPcp prior = VlanPcp.of(get_byte(n.group(1)));
				OFActionSetVlanPcp.Builder ab = OFFactories.getFactory(version).actions().buildSetVlanPcp();
				ab.setVlanPcp(prior);
				log.debug("action {}", ab.build());
				return ab.build();
			}
			catch (NumberFormatException e) {
				log.debug("Invalid VLAN priority in: {} (error ignored)", actionToDecode);
				return null;
			}
		}
	}
	else {
		log.debug("Invalid action: '{}'", actionToDecode);
		return null;
	}
	return null;
}
 
Example 3
Project: habpanelviewer   File: ScreenController.java   View source code 6 votes vote down vote up
public void updateFromPreferences(SharedPreferences prefs) {
    screenOnPattern = null;
    screenOnItemName = prefs.getString("pref_screen_item", "");

    enabled = prefs.getBoolean("pref_screen_enabled", false);
    keepOn = prefs.getBoolean("pref_screen_stay_enabled", false);

    String onRegexpStr = prefs.getString("pref_screen_on_regex", "");
    if (!onRegexpStr.isEmpty()) {
        try {
            screenOnPattern = Pattern.compile(onRegexpStr);
        } catch (PatternSyntaxException e) {
            // is handled in the preferences
        }
    }

    mServerConnection.subscribeItems(this, screenOnItemName);
}
 
Example 4
Project: neoscada   File: AknProxyItemProvider.java   View source code 6 votes vote down vote up
/**
 * This returns the label styled text for the adapted class.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public Object getStyledText ( Object object )
{
    Pattern labelValue = ( (AknProxy)object ).getPattern ();
    String label = labelValue == null ? null : labelValue.toString ();
    StyledString styledLabel = new StyledString ();
    if ( label == null || label.length () == 0 )
    {
        styledLabel.append ( getString ( "_UI_AknProxy_type" ), StyledString.Style.QUALIFIER_STYLER ); //$NON-NLS-1$
    }
    else
    {
        styledLabel.append ( getString ( "_UI_AknProxy_type" ), StyledString.Style.QUALIFIER_STYLER ).append ( " " + label ); //$NON-NLS-1$ //$NON-NLS-2$
    }
    return styledLabel;
}
 
Example 5
Project: incubator-netbeans   File: TextValueCompleter.java   View source code 6 votes vote down vote up
@NbBundle.Messages("PARTIAL_RESULT=<Result is incomplete, some indices are processed>")
private void buildPopup() {
    pattern = Pattern.compile(getCompletionPrefix() + ".+"); //NOI18N
    int entryindex = 0;
    for (String completion : completions) {
        // check if match
        Matcher matcher = pattern.matcher(completion);
        if (matcher.matches()) {
            if (!completionListModel.contains(completion)) {
                completionListModel.add(entryindex,
                        completion);
            }
            entryindex++;
        } else {
            completionListModel.removeElement(completion);
        }
    }
    completionListModel.removeElement(Bundle.PARTIAL_RESULT());
    if (partial) {
        completionListModel.addElement(Bundle.PARTIAL_RESULT());
    }
}
 
Example 6
Project: Jupiter   File: Item.java   View source code 6 votes vote down vote up
public static Item fromString(String str) {
    String[] b = str.trim().replace(' ', '_').replace("minecraft:", "").split(":");

    int id = 0;
    int meta = 0;

    Pattern integerPattern = Pattern.compile("^[1-9]\\d*$");
    if (integerPattern.matcher(b[0]).matches()) {
        id = Integer.valueOf(b[0]);
    } else {
        try {
            id = Item.class.getField(b[0].toUpperCase()).getInt(null);
        } catch (Exception ignore) {
        }
    }

    id = id & 0xFFFF;
    if (b.length != 1) meta = Integer.valueOf(b[1]) & 0xFFFF;

    return get(id, meta);
}
 
Example 7
Project: karate   File: FilterFormatter.java   View source code 6 votes vote down vote up
private Filter detectFilter(List filters) {
    Set<Class> filterClasses = new HashSet<Class>();
    for (Object filter : filters) {
        filterClasses.add(filter.getClass());
    }
    if (filterClasses.size() > 1) {
        throw new IllegalArgumentException("Inconsistent filters: " + filters + ". Only one type [line,name,tag] can be used at once.");
    }

    Class<?> typeOfFilter = filters.get(0).getClass();
    if (String.class.isAssignableFrom(typeOfFilter)) {
        return new TagFilter(filters);
    } else if (Number.class.isAssignableFrom(typeOfFilter)) {
        return new LineFilter(filters);
    } else if (Pattern.class.isAssignableFrom(typeOfFilter)) {
        return new PatternFilter(filters);
    } else {
        throw new RuntimeException("Could not create filter method for unknown filter of type: " + typeOfFilter);
    }
}
 
Example 8
Project: springboot-shiro-cas-mybatis   File: GoogleAccountsServiceTests.java   View source code 6 votes vote down vote up
@Test
public void verifyResponse() {
    final Response resp = this.googleAccountsService.getResponse("ticketId");
    assertEquals(resp.getResponseType(), DefaultResponse.ResponseType.POST);
    final String response = resp.getAttributes().get(SamlProtocolConstants.PARAMETER_SAML_RESPONSE);
    assertNotNull(response);
    assertTrue(response.contains("NotOnOrAfter"));

    final Pattern pattern = Pattern.compile("NotOnOrAfter\\s*=\\s*\"(.+Z)\"");
    final Matcher matcher = pattern.matcher(response);
    final DateTime now = DateTime.parse(new ISOStandardDateFormat().getCurrentDateAndTime());

    while (matcher.find()) {
        final String onOrAfter = matcher.group(1);
        final DateTime dt = DateTime.parse(onOrAfter);
        assertTrue(dt.isAfter(now));
    }
    assertTrue(resp.getAttributes().containsKey(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE));
}
 
Example 9
Project: OpenDA   File: DictionaryTimeSeriesDataObject.java   View source code 6 votes vote down vote up
/** {@inheritDoc}
 */
public IExchangeItem getDataObjectExchangeItem(String exchangeItemID) {

    String[] parts = Pattern.compile(idSeparator, Pattern.LITERAL).split(exchangeItemID);
    if (parts.length != 2) {
        throw new RuntimeException("Invalid exchangeItemID " + exchangeItemID );
    }
    String location = parts[0];
    String quantity = parts[1];


    // Get the single time series based on location and quantity
    TimeSeriesSet myTimeSeriesSet = this.timeSeriesSet.getOnQuantity(quantity)
        .getOnLocation(location);
    Iterator<TimeSeries> iterator = myTimeSeriesSet.iterator();
    if (!iterator.hasNext()) {
        throw new RuntimeException("No time series found for " + exchangeItemID);
    }
    TimeSeries timeSeries = iterator.next();
    if (iterator.hasNext()) {
        throw new RuntimeException("Time series is not uniquely defined for  " + exchangeItemID);
    }
    return timeSeries;


}
 
Example 10
Project: wirtualnaApteczka   File: MedicineFilter.java   View source code 6 votes vote down vote up
public static List<Medicine> filterMedicines(String searchValue, List<Medicine> medicines, boolean exactMatches) {
    List<Medicine> filteredMedicines = new ArrayList<>();

    if (TextUtils.isEmpty(searchValue)) {
        filteredMedicines = medicines;
    }

    if (CollectionUtils.isNotEmpty(medicines) && !TextUtils.isEmpty(searchValue)) {
        String patternRegex = prepareRegexPattern(searchValue, exactMatches);
        Pattern pattern = Pattern.compile(patternRegex);
        Matcher matcher;

        for (Medicine medicine : medicines) {
            matcher = pattern.matcher(medicine.getName());

            if (matcher.matches()) {
                filteredMedicines.add(medicine);
            }
        }
    }

    return filteredMedicines;
}
 
Example 11
Project: hanlpStudy   File: StringUtils.java   View source code 5 votes vote down vote up
public static String replaceSpecialtyStr(String str, String pattern, String replace)
{
    if (isBlankOrNull(pattern))
        pattern = "\\s*|\t|\r|\n";//去除字符串中空格、换行、制表
    if (isBlankOrNull(replace))
        replace = "";
    return Pattern.compile(pattern).matcher(str).replaceAll(replace);

}
 
Example 12
Project: convertigo-engine   File: UIText.java   View source code 5 votes vote down vote up
@Override
public boolean updateSmartSource(String oldString, String newString) {
	String smartValue = textValue.getSmartValue();
	if (smartValue.indexOf(oldString) != -1 || Pattern.compile(oldString).matcher(smartValue).find()) {
		textValue.setSmartValue(smartValue.replaceAll(oldString, newString));
		this.hasChanged = true;
	}
	boolean updated = super.updateSmartSource(oldString, newString);
	return updated || this.hasChanged;
}
 
Example 13
Project: Maxine-VM   File: VMAOptions.java   View source code 5 votes vote down vote up
/**
 * Check if bytecode:advice combination is matched by the provided pattern.
 * @param pattern
 * @param b
 */
private static void matchBytecode(Pattern pattern, VMABytecodes b, boolean[] state, boolean setting) {
    final String name = b.name();
    if (pattern.matcher(name).matches() || pattern.matcher(name + ":AB").matches()) {
        state[0] = setting;
        state[1] = setting;
    } else if (pattern.matcher(name + ":B").matches()) {
        state[0] = setting;
    } else if (pattern.matcher(name + ":A").matches()) {
        state[1] = setting;
    }
}
 
Example 14
Project: https-github.com-apache-zookeeper   File: KerberosName.java   View source code 5 votes vote down vote up
Rule(int numOfComponents, String format, String match, String fromPattern,
     String toPattern, boolean repeat) {
  isDefault = false;
  this.numOfComponents = numOfComponents;
  this.format = format;
  this.match = match == null ? null : Pattern.compile(match);
  this.fromPattern = 
    fromPattern == null ? null : Pattern.compile(fromPattern);
  this.toPattern = toPattern;
  this.repeat = repeat;
}
 
Example 15
Project: headb   File: HStringUtils.java   View source code 5 votes vote down vote up
/**
 * 是否为英文
 * 
 * @param checkValue
 * @return boolean
 */
public static boolean isEnglish(String checkValue) {
	String el = "^[A-Za-z]+$";
	Pattern p = Pattern.compile(el);
	Matcher m = p.matcher(checkValue);
	return m.matches();
}
 
Example 16
Project: weex-svg   File: ParserHelper.java   View source code 5 votes vote down vote up
/**
 * Converts percentage string into actual based on a relative number
 *
 * @param percentage percentage string
 * @param relative   relative number
 * @param offset     offset number
 * @return actual float based on relative number
 */
public static float fromPercentageToFloat(String percentage, float relative, float offset, float scale) {
  Matcher matched = Pattern.compile("^(\\-?\\d+(?:\\.\\d+)?)%$").matcher(percentage);
  if (matched.matches()) {
    return Float.valueOf(matched.group(1)) / 100 * relative + offset;
  } else {
    return Float.valueOf(percentage) * scale;
  }
}
 
Example 17
Project: Parabot-317-API-Minified-OS-Scape   File: MessageInjector.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void run(ClassNode classNode) {
    for (MethodNode methodNode : (List<MethodNode>) classNode.methods) {
        if (methodNode.name.equals(Hook.getInstance().getField("getMessageCallback", true).replaceAll(Pattern.quote("."), "/"))) {
            if (methodNode.desc.equals("(ILjava/lang/String;Ljava/lang/String;)V")) {
                System.out.println("We found MessageCallBack method.");
                callBack(methodNode);
                break;
            }

        }
    }

}
 
Example 18
Project: OSchina_resources_android   File: RichTextParser.java   View source code 5 votes vote down vote up
/**
 * @param sequence       文本
 * @param pattern        正则
 * @param usedGroupIndex 使用的组号
 * @param showGroupIndex 显示的组号
 * @param listener       点击回掉
 * @return 匹配后的文本
 */
@SuppressWarnings("all")
private static Spannable assimilate(CharSequence sequence,
                                    Pattern pattern,
                                    int usedGroupIndex,
                                    int showGroupIndex,
                                    final OnClickListener listener) {
    SpannableStringBuilder builder = new SpannableStringBuilder(sequence);
    Matcher matcher;
    while (true) {
        matcher = pattern.matcher(builder.toString());
        if (matcher.find()) {
            final String group0 = matcher.group(usedGroupIndex);
            final String group1 = matcher.group(showGroupIndex);
            builder.replace(matcher.start(), matcher.end(), group1);
            ClickableSpan span = new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    listener.onClick(group0);
                }
            };
            builder.setSpan(span, matcher.start(), matcher.start() + group1.length(),
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            continue;
        }
        break;
    }
    return builder;
}
 
Example 19
Project: javaide   File: Grep.java   View source code 5 votes vote down vote up
private Set<Integer> getStringIds(Dex dex, Pattern pattern) {
    Set<Integer> stringIds = new HashSet<Integer>();
    int stringIndex = 0;
    for (String s : dex.strings()) {
        if (pattern.matcher(s).find()) {
            stringIds.add(stringIndex);
        }
        stringIndex++;
    }
    return stringIds;
}
 
Example 20
Project: xdman   File: RegexFTPFileEntryParserImpl.java   View source code 5 votes vote down vote up
/**
 * Alter the current regular expression being utilised for entry parsing
 * and create a new {@link Pattern} instance.
 * @param regex The new regular expression
 * @return  true if the compiled pattern is not null
 * @since 2.0
 */
public boolean setRegex(String regex) {
    try {
        pattern = Pattern.compile(regex);
    } catch (PatternSyntaxException pse) {
        throw new IllegalArgumentException("Unparseable regex supplied: "
                + regex);
    }
    return (pattern != null);
}
 
Example 21
Project: spring-cloud-skipper   File: ArgumentSanitizer.java   View source code 5 votes vote down vote up
/**
 * Replaces a potential secure value with "******".
 *
 * @param key to evaluate if its value should be redacted.
 * @return true if result needs to be sanitized.
 */
private static boolean toBeSanitized(String key) {
	boolean result = false;
	for (Pattern pattern : keysToSanitize) {
		if (pattern.matcher(key).matches()) {
			result = true;
			break;
		}
	}
	return result;
}
 
Example 22
Project: openjdk-jdk10   File: Test1b.java   View source code 5 votes vote down vote up
void run(String... args) throws Exception {
    File testSrcDir = new File(System.getProperty("test.src"));
    File tmpClassDir = new File(".");
    List<String> l = new ArrayList<String>();
    l.add("-d");
    l.add(tmpClassDir.getPath());
    for (String a: args) {
        if (a.endsWith(".java"))
            l.add(new File(testSrcDir, a).getPath());
        else
            l.add(a);
    }

    StringWriter sw = new StringWriter();
    int rc = com.sun.tools.javac.Main.compile(l.toArray(new String[l.size()]), new PrintWriter(sw));
    System.err.println(sw);

    Pattern p = Pattern.compile("([A-Z]+).*");
    for (String name: tmpClassDir.list()) {
        if (name.endsWith(".class")) {
            Matcher m = p.matcher(name);
            if (m.matches()) {
                found(m.group(1), name);
            }
        }
    }

    // for all classes that might have been compiled, check that
    // all the classes in the source file get generated, or none do.
    check("A", 3);
    check("B", 3);
    check("C", 3);
    check("D", 3);

    if (errors > 0)
        throw new Exception(errors + " errors");
}
 
Example 23
Project: NetDiscovery   File: RegexSelector.java   View source code 5 votes vote down vote up
private void compileRegex(String regexStr) {
    if (Preconditions.isBlank(regexStr)) {
        throw new IllegalArgumentException("regex must not be empty");
    }
    try {
        this.regex = Pattern.compile(regexStr, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
        this.regexStr = regexStr;
    } catch (PatternSyntaxException e) {
        throw new IllegalArgumentException("invalid regex "+regexStr, e);
    }
}
 
Example 24
Project: sonar-css-plugin   File: TrailingWhitespaceCheck.java   View source code 5 votes vote down vote up
@Override
public void visitStyleSheet(StyleSheetTree tree) {
  List<String> lines;
  try {
    lines = Files.readLines(getContext().getFile(), charset);
  } catch (IOException e) {
    throw new IllegalStateException("Check css:" + this.getClass().getAnnotation(Rule.class).key()
      + ": Error while reading " + getContext().getFile().getName(), e);
  }
  for (int i = 0; i < lines.size(); i++) {
    String line = lines.get(i);
    if (line.length() > 0 && Pattern.matches("[" + WHITESPACE + "]", line.subSequence(line.length() - 1, line.length()))) {
      addLineIssue(i + 1, "Remove the useless trailing whitespaces at the end of this line.");
    }
  }
  super.visitStyleSheet(tree);
}
 
Example 25
Project: renren-fast   File: HTMLFilter.java   View source code 5 votes vote down vote up
private String processRemoveBlanks(final String s) {
    String result = s;
    for (String tag : vRemoveBlanks) {
        if(!P_REMOVE_PAIR_BLANKS.containsKey(tag)){
            P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
        }
        result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
        if(!P_REMOVE_SELF_BLANKS.containsKey(tag)){
            P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
        }
        result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
    }

    return result;
}
 
Example 26
Project: kafka-0.11.0.0-src-with-comment   File: TopologyBuilderTest.java   View source code 5 votes vote down vote up
@Test
public void shouldAddSourcePatternWithOffsetReset() {
    final TopologyBuilder builder = new TopologyBuilder();
    
    final String earliestTopicPattern = "earliest.*Topic";
    final String latestTopicPattern = "latest.*Topic";

    builder.addSource(TopologyBuilder.AutoOffsetReset.EARLIEST, "source", Pattern.compile(earliestTopicPattern));
    builder.addSource(TopologyBuilder.AutoOffsetReset.LATEST, "source2", Pattern.compile(latestTopicPattern));

    assertTrue(builder.earliestResetTopicsPattern().matcher("earliestTestTopic").matches());
    assertTrue(builder.latestResetTopicsPattern().matcher("latestTestTopic").matches());
}
 
Example 27
Project: OpenJSharp   File: WindowsFileSystem.java   View source code 5 votes vote down vote up
@Override
public PathMatcher getPathMatcher(String syntaxAndInput) {
    int pos = syntaxAndInput.indexOf(':');
    if (pos <= 0 || pos == syntaxAndInput.length())
        throw new IllegalArgumentException();
    String syntax = syntaxAndInput.substring(0, pos);
    String input = syntaxAndInput.substring(pos+1);

    String expr;
    if (syntax.equals(GLOB_SYNTAX)) {
        expr = Globs.toWindowsRegexPattern(input);
    } else {
        if (syntax.equals(REGEX_SYNTAX)) {
            expr = input;
        } else {
            throw new UnsupportedOperationException("Syntax '" + syntax +
                "' not recognized");
        }
    }

    // match in unicode_case_insensitive
    final Pattern pattern = Pattern.compile(expr,
        Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);

    // return matcher
    return new PathMatcher() {
        @Override
        public boolean matches(Path path) {
            return pattern.matcher(path.toString()).matches();
        }
    };
}
 
Example 28
Project: APIJSON-Android-RxJava   File: StringUtil.java   View source code 5 votes vote down vote up
public static boolean isEmail(String email) {
	if (isNotEmpty(email, true) == false) {
		return false;
	}

	String str = "^([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})(\\]?)$";
	Pattern p = Pattern.compile(str);

	currentString = email;

	return p.matcher(email).matches();
}
 
Example 29
Project: renren-msg   File: HTMLFilter.java   View source code 5 votes vote down vote up
private String processRemoveBlanks(final String s) {
    String result = s;
    for (String tag : vRemoveBlanks) {
        if(!P_REMOVE_PAIR_BLANKS.containsKey(tag)){
            P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">"));
        }
        result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result);
        if(!P_REMOVE_SELF_BLANKS.containsKey(tag)){
            P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>"));
        }
        result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result);
    }

    return result;
}
 
Example 30
Project: EVideoRecorder   File: StringUtil.java   View source code 5 votes vote down vote up
/**
 * 在String中输出keyword的position合集
 *
 * @param regex keywords
 * @param text  text
 * @return ArrayList<Integer>
 */
public static ArrayList<Integer> searchTextFromString(String regex, String text) {
    ArrayList<Integer> mList = new ArrayList<>();
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        mList.add(matcher.start());
        mList.add(matcher.end());
    }
    return mList;
}
 
Example 31
Project: jspider   File: DefaultValuesHolder.java   View source code 5 votes vote down vote up
public Map<String, List<String>> getValuesMap(String holderText) {
    Map<String, List<String>> valuesMap = new HashMap<String, List<String>>();
    Matcher matcher = Pattern.compile("\\{(.*?)\\}").matcher(holderText);
    while (matcher.find()) {
        String text = matcher.group();
        if (!isValidHolder(text)) {
            continue;
        }
        List<String> list = getValues(text);
        valuesMap.put(text, list);
    }
    return valuesMap;
}
 
Example 32
Project: letv   File: SignSharePageEditActivity.java   View source code 5 votes vote down vote up
public int counts(String text) {
    int doubleC = 0;
    while (Pattern.compile("[^\\x00-\\xff]").matcher(text).find()) {
        doubleC++;
    }
    int singelC = text.length() - doubleC;
    if (singelC % 2 != 0) {
        return doubleC + ((singelC + 1) / 2);
    }
    return doubleC + (singelC / 2);
}
 
Example 33
Project: hadoop-oss   File: RunJar.java   View source code 5 votes vote down vote up
/**
 * Unpack matching files from a jar. Entries inside the jar that do
 * not match the given pattern will be skipped.
 *
 * @param jarFile the .jar file to unpack
 * @param toDir the destination directory into which to unpack the jar
 * @param unpackRegex the pattern to match jar entries against
 */
public static void unJar(File jarFile, File toDir, Pattern unpackRegex)
  throws IOException {
  JarFile jar = new JarFile(jarFile);
  try {
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
      final JarEntry entry = entries.nextElement();
      if (!entry.isDirectory() &&
          unpackRegex.matcher(entry.getName()).matches()) {
        InputStream in = jar.getInputStream(entry);
        try {
          File file = new File(toDir, entry.getName());
          ensureDirectory(file.getParentFile());
          OutputStream out = new FileOutputStream(file);
          try {
            IOUtils.copyBytes(in, out, 8192);
          } finally {
            out.close();
          }
        } finally {
          in.close();
        }
      }
    }
  } finally {
    jar.close();
  }
}
 
Example 34
Project: koans   File: AboutRegularExpressions.java   View source code 5 votes vote down vote up
@Koan
public void basicMatching() {
    Pattern p = Pattern.compile("xyz");
    Matcher m = p.matcher("xyzxxxxyz");
    // index 012345678
    assertEquals(m.find(), __);
    assertEquals(m.start(), __);
    assertEquals(m.find(), __);
    assertEquals(m.start(), __);
    assertEquals(m.find(), __);
}
 
Example 35
Project: ripme   File: XhamsterRipper.java   View source code 5 votes vote down vote up
@Override
public String getGID(URL url) throws MalformedURLException {
    Pattern p = Pattern.compile("^https?://.*xhamster\\.com/(movies|videos)/(.*)$");
    Matcher m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return m.group(2);
    }

    throw new MalformedURLException(
            "Expected xhamster format:"
                    + "xhamster.com/movies/#### or"
                    + "xhamster.com/videos/####"
                    + " Got: " + url);
}
 
Example 36
Project: hy.common.base   File: StringHelp.java   View source code 5 votes vote down vote up
/**
 * 正则表达式验证邮箱格式
 * 
 * @param i_EMail
 * @return
 */
public final static boolean isEMail(String i_EMail)
{
    if ( Help.isNull(i_EMail) )
    {
        return false;
    }
    
    return Pattern.matches($EMail ,i_EMail);
}
 
Example 37
Project: jmzTab-m   File: MZTabError.java   View source code 5 votes vote down vote up
/**
 * fill "{id}" parameter list one by one.
 */
private String fill(int count, List<String> values, String message) {
    String regexp = "\\{\\w\\}";
    Pattern pattern = Pattern.compile(regexp);
    Matcher matcher = pattern.matcher(message);

    String value;
    if (matcher.find()) {
        value = values.get(count);
        message = matcher.replaceFirst(value);
        return fill(count + 1, values, message);
    } else {
        return message;
    }
}
 
Example 38
Project: bootstrap   File: SessionResource.java   View source code 5 votes vote down vote up
/**
 * Add roles and authorizations.
 */
private void addAuthorizations(final SessionSettings settings) {
	final List<String> rolesAsString = getRolesAsString();
	settings.setRoles(rolesAsString);

	// Add authorizations
	final Map<AuthorizationType, Map<String, Map<HttpMethod, List<Pattern>>>> cache = authorizationResource.getAuthorizations();
	settings.setAuthorizations(toPatterns(filterRoles(cache.get(AuthorizationType.UI), rolesAsString)));
	settings.setBusinessAuthorizations(getBusinessAuthorizations(filterRoles(cache.get(AuthorizationType.API), rolesAsString)));
}
 
Example 39
Project: uavstack   File: ThreadAnalysisAction.java   View source code 5 votes vote down vote up
private boolean validateMailAddress(String address) {

        Pattern p = Pattern.compile("^[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
        Matcher matcher = null;
        String[] addr = address.split(",");
        for (int i = 0; i < addr.length; i++) {
            matcher = p.matcher(addr[i].trim());
            if (!matcher.matches()) {
                return false;
            }
        }
        return true;
    }
 
Example 40
Project: GxIconAndroid   File: ResChecker.java   View source code 5 votes vote down vote up
private static void checkAppFilter(String xmlDirPath) {
    String appFilterText = FileUtil.readFile(new File(new File(xmlDirPath), "appfilter.xml"));
    String drawableText = FileUtil.readFile(new File(new File(xmlDirPath), "drawable.xml"));
    
    Matcher matcher = Pattern.compile("drawable=\"(.+?)\"").matcher(appFilterText);
    while (matcher.find()) {
        if (!drawableText.contains("\"" + matcher.group(1) + "\"")) {
            System.out.println("Lost: " + matcher.group(1));
        }
    }
}