Java Code Examples for java.util.regex.Matcher

The following are top voted examples for showing how to use java.util.regex.Matcher. 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: marathonv5   File: JavaFXTabPaneElement.java   View source code 7 votes vote down vote up
@Override public boolean marathon_select(String tab) {
    Matcher matcher = CLOSE_PATTERN.matcher(tab);
    boolean isCloseTab = matcher.matches();
    tab = isCloseTab ? matcher.group(1) : tab;
    TabPane tp = (TabPane) node;
    ObservableList<Tab> tabs = tp.getTabs();
    for (int index = 0; index < tabs.size(); index++) {
        String current = getTextForTab(tp, tabs.get(index));
        if (tab.equals(current)) {
            if (isCloseTab) {
                ((TabPaneSkin) tp.getSkin()).getBehavior().closeTab(tabs.get(index));
                return true;
            }
            tp.getSelectionModel().select(index);
            return true;
        }
    }
    return false;
}
 
Example 2
Project: krobot   File: CommandManager.java   View source code 6 votes vote down vote up
/**
 * Split a message from whitespaces, ignoring the one in quotes.<br><br>
 *
 * <b>Example :</b>
 *
 * <pre>
 *     I am a "discord bot"
 * </pre>
 *
 * Will return ["I", "am", "a", "discord bot"].
 *
 * @param line The line to split
 *
 * @return The line split
 */
public static String[] splitWithQuotes(String line)
{
    ArrayList<String> matchList = new ArrayList<>();
    Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
    Matcher matcher = regex.matcher(line);

    while (matcher.find())
    {
        if (matcher.group(1) != null)
        {
            matchList.add(matcher.group(1));
        }
        else if (matcher.group(2) != null)
        {
            matchList.add(matcher.group(2));
        }
        else
        {
            matchList.add(matcher.group());
        }
    }

    return matchList.toArray(new String[matchList.size()]);
}
 
Example 3
Project: JavaCommon   File: RegexDemo.java   View source code 6 votes vote down vote up
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 4
Project: oryx2   File: DeleteOldDataFn.java   View source code 6 votes vote down vote up
@Override
public void call(T ignored) throws IOException {
  Path dataDirPath = new Path(dataDirString + "/*");
  FileSystem fs = FileSystem.get(dataDirPath.toUri(), hadoopConf);
  FileStatus[] inputPathStatuses = fs.globStatus(dataDirPath);
  if (inputPathStatuses != null) {
    long oldestTimeAllowed =
        System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(maxAgeHours, TimeUnit.HOURS);
    Arrays.stream(inputPathStatuses).filter(FileStatus::isDirectory).map(FileStatus::getPath).
        filter(subdir -> {
          Matcher m = dirTimestampPattern.matcher(subdir.getName());
          return m.find() && Long.parseLong(m.group(1)) < oldestTimeAllowed;
        }).forEach(subdir -> {
          log.info("Deleting old data at {}", subdir);
          try {
            fs.delete(subdir, true);
          } catch (IOException e) {
            log.warn("Unable to delete {}; continuing", subdir, e);
          }
        });
  }
}
 
Example 5
Project: incubator-ratis   File: Assign.java   View source code 6 votes vote down vote up
@VisibleForTesting
protected Expression createExpression(String value) {
  if (value.matches("\\d*(\\.\\d*)?")) {
    return new DoubleValue(Double.valueOf(value));
  } else if (value.matches("[a-zA-Z]+")) {
    return new Variable(value);
  }
  Matcher binaryMatcher = binaryOperationPattern.matcher(value);
  Matcher unaryMatcher = unaryOperationPattern.matcher(value);

  if (binaryMatcher.matches()) {
    return createBinaryExpression(binaryMatcher);
  } else if (unaryMatcher.matches()) {
    return createUnaryExpression(unaryMatcher);
  } else {
    throw new IllegalArgumentException("Invalid expression " + value + " Try something like: 'a+b' or '2'");
  }
}
 
Example 6
Project: dremio-oss   File: GlobalDictionaryBuilder.java   View source code 6 votes vote down vote up
/**
 * @param fs Filesystem
 * @param tableDir root of parquet table
 * @return the highest dictionary version found, -1 if no dictionaries are present
 * @throws IOException
 */
public static long getDictionaryVersion(FileSystem fs, Path tableDir) throws IOException {
  final FileStatus[] statuses = fs.listStatus(tableDir, DICTIONARY_ROOT_FILTER);
  long maxVersion = -1;
  for (FileStatus status : statuses) {
    if (status.isDirectory()) {
      Matcher matcher = DICTIONARY_VERSION_PATTERN.matcher(status.getPath().getName());
      if (matcher.find()) {
        try {
          final long version = Long.parseLong(matcher.group(1));
          if (version > maxVersion) {
            maxVersion = version;
          }
        } catch (NumberFormatException nfe) {
        }
      }
    }
  }
  return maxVersion;
}
 
Example 7
Project: VanillaPlus   File: SPHSuffix.java   View source code 6 votes vote down vote up
public HashMap<String, List<SPH>> getPHs(String message){
	Matcher m = pattern.matcher(message);
	HashMap<String, List<SPH>>result = new HashMap<String, List<SPH>>();
	while (m.find()) {
		String key = m.group(1);
		List<SPH>s = result.get(key);
		if(s==null){
			s=new ArrayList<SPH>();
			result.put(key, s);
		}
		String suffix = null;
		if(m.groupCount() > 1){
			suffix = m.group(2);
		}
		s.add(getInstance(suffix));
	}
	return result;
}
 
Example 8
Project: lams   File: MockLearner.java   View source code 6 votes vote down vote up
private WebResponse handleToolLeader(WebResponse resp) throws SAXException, IOException {
String asText = resp.getText();
Matcher m = MockLearner.LEADER_SHOW_DIALOG_PATTERN.matcher(asText);
if (!m.find()) {
    throw new TestHarnessException("Could not tell whether the user can become the leader");
}
if (Boolean.valueOf(m.group(1))) {
    m = MockLearner.LEADER_BECOME_PATTERN.matcher(asText);
    if (!m.find()) {
	throw new TestHarnessException("Could not \"become leader\" URL");
    }
    String becomeLeaderQueryOptions = m.group();
    String url = "/lams/tool/lalead11/learning.do?" + becomeLeaderQueryOptions;
    MockLearner.log.debug("Becoming a leader using link: " + url);
    new Call(wc, test, username + " becomes Leader", url).execute();
}
String finishURL = MockLearner.findURLInLocationHref(resp, MockLearner.LEADER_FINISH_SUBSTRING);
if (finishURL == null) {
    throw new TestHarnessException("Unable to finish the leader, no finish link found. " + asText);
}

MockLearner.log.debug("Ending leader using url " + finishURL);
return (WebResponse) new Call(wc, test, username + " finishes Leader", finishURL).execute();
   }
 
Example 9
Project: visual-spider   File: Crawler.java   View source code 6 votes vote down vote up
/**
 * 判断需要下载的资源
 * 
 * @param url
 *            {@link URL}
 * @param html
 *            {@link String}
 */
public void downloadURL(String url, String html) {
	Matcher matcher;
	if (CrawlConfig.getCrawlImages().get()) {
		matcher = IMAGES_PATTERN.matcher(html);
		addURLs("image", matcher);
	}
	if (CrawlConfig.getCrawlVideos().get()) {
		matcher = VIDEOS_PATTERN.matcher(html);
		addURLs("media", matcher);
	}
	if (CrawlConfig.getCrawlDocs().get()) {
		matcher = DOCS_PATTERN.matcher(html);
		addURLs("document", matcher);
	}
	if (CrawlConfig.getCrawlOthers().get()) {
		matcher = OTHERS_PATTERN.matcher(html);
		addURLs("others", matcher);
	}
	if (Checker.isNotEmpty(url) && CrawlConfig.getCrawlLinks().get()) {
		String path = App.DOWNLOAD_FOLDER + Values.SEPARATOR + "link";
		Downloader.download(path, (url.startsWith("//") ? "http:" : "") + url);
	}
}
 
Example 10
Project: read_13f   File: File_Processor_Old.java   View source code 6 votes vote down vote up
private List<Integer> regex_offset(String line) {

        List<Integer> found_offsets = new ArrayList<>();

        // Cusips are 9 characters and can contain numbers and letters
        String pattern = "[A-Za-z0-9]{9}";
        Pattern finder = Pattern.compile(pattern);
        Matcher matcher = finder.matcher(line);

        // Every candidate gets added to the list
        while (matcher.find()) {
            found_offsets.add(matcher.start());
        }

        return found_offsets;
    }
 
Example 11
Project: sonar-quality-gates-plugin   File: JobConfigurationService.java   View source code 6 votes vote down vote up
private String resolveEmbeddedEnvVariables(final String projectKey, final EnvVars env, final Pattern pattern, final int braceOffset) {

        final Matcher matcher = pattern.matcher(projectKey);
        final StringBuilder builder = new StringBuilder(projectKey);
        boolean matchesFound = false;
        int offset = 0;

        while (matcher.find()) {
            final String envVariable = projectKey.substring(matcher.start() + braceOffset + 1, matcher.end() - braceOffset);
            final String envValue = env.get(envVariable);

            if (envValue == null) {
                throw new QGException("Environment Variable [" + envVariable + "] not found");
            }

            builder.replace(matcher.start() + offset, matcher.end() + offset, envValue);
            offset += envValue.length() - matcher.group(1).length();
            matchesFound = true;
        }

        if (matchesFound) {
            return getProjectKey(builder.toString(), env);
        }

        return builder.toString();
    }
 
Example 12
Project: cas-5.1.0   File: ScriptedRegisteredServiceAttributeReleasePolicy.java   View source code 6 votes vote down vote up
@Override
protected Map<String, Object> getAttributesInternal(final Principal principal,
                                                    final Map<String, Object> attributes,
                                                    final RegisteredService service) {
    try {
        if (StringUtils.isBlank(this.scriptFile)) {
            return new HashMap<>();
        }
        final Matcher matcherInline = INLINE_GROOVY_PATTERN.matcher(this.scriptFile);
        if (matcherInline.find()) {
            return getAttributesFromInlineGroovyScript(attributes, matcherInline);
        }
        return getScriptedAttributesFromFile(attributes);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return new HashMap<>();
}
 
Example 13
Project: Word2VecfJava   File: ExpressionParser.java   View source code 6 votes vote down vote up
public ExpressionParser parse() {
	Matcher matcher = this.pattern.matcher(this.query);
	List<String> matches = new ArrayList<>();
	while (matcher.find()) matches.add(matcher.group());
	terms = new ArrayList<>();
	operations = new ArrayList<>();
	String global = "";
	for (String string : matches) {
		if (string.equals(PLUS) || string.equals(MINUS)) {
			operations.add(string);
		} else {
			global = global.concat(string);
			terms.add(cleanString(string));
		}
	}
	Matcher matcher2 = this.pattern2.matcher(this.query);
	while (matcher2.find()) operations.add(matcher2.group());
	terms.add(this.query.replace(global, "").trim());
	return this;
}
 
Example 14
Project: wish-pay   File: HttpClientUtils.java   View source code 6 votes vote down vote up
/**
 * @param url
 * @param paramsMap
 * @return
 * @Description 检测url中是否有restful风格的占位符,比如/{sessionId}/token中的sessionId,从paramsMap中替换
 */
private static String checkHashRestfulPlaceholder(String url, Map<String, Object> paramsMap) {
    Pattern pattern = Pattern.compile("(\\{\\w+\\})");
    Matcher matcher = pattern.matcher(url);

    String resultUrl = url;

    String plaseholder = "";
    String mapKey = "";
    while (matcher.find()) {
        plaseholder = matcher.group(1);
        mapKey = plaseholder.substring(1, plaseholder.length() - 1);
        //如果有占位符Map中未get到,直接跳出这组指标规则循环继续下一组
        resultUrl = url.replace(plaseholder, String.valueOf(paramsMap.get(mapKey)));
    }
    return resultUrl;
}
 
Example 15
Project: JLink   File: SimpleRegexTokenizer.java   View source code 6 votes vote down vote up
public List<Tokenization> tokenize(List<String> sentences) {
	List<Tokenization> tokenizations = new ArrayList<>();
	int accumulatedSentenceLength = 0;
	for (String sentence : sentences) {
		int index = 0;
		Matcher matcher = pattern.matcher(sentence);
		List<Token> tokens = new ArrayList<>();
		while (matcher.find()) {
			String text = matcher.group();
			int from = matcher.start();
			int to = matcher.end();
			tokens.add(new Token(index, from, to, text));
			index++;
		}
		Tokenization tokenization = new Tokenization(tokens, sentence, accumulatedSentenceLength);
		tokenizations.add(tokenization);
		accumulatedSentenceLength += sentence.length();
		// System.out.println(tokenization.originalSentence);
		// System.out.println(
		// tokenization.tokens.stream().reduce("", (s, t) -> s + " " +
		// t.getText(), (s, tt) -> s + tt));
	}
	return tokenizations;
}
 
Example 16
Project: defense-solutions-proofs-of-concept   File: CoTAdapter.java   View source code 6 votes vote down vote up
private String convertType(String type) {

		Matcher matcher;
		for (CoTTypeDef cd : this.coTTypeMap) {
			if (!cd.isPredicate()) {
				Pattern pattern = Pattern.compile(cd.getKey());
				matcher = pattern.matcher(type);
				if (matcher.find()) {

					return this.filterOutDots(appendToType(type)
							+ cd.getValue());

				}

			}

		}
		// no match was found
		return "";

	}
 
Example 17
Project: dremio-oss   File: ShowSchemasHandler.java   View source code 6 votes vote down vote up
@Override
public List<SchemaResult> toResult(String sql, SqlNode sqlNode) throws Exception {
  final SqlShowSchemas node = SqlNodeUtil.unwrap(sqlNode, SqlShowSchemas.class);
  final Pattern likePattern = SqlNodeUtil.getPattern(node.getLikePattern());
  final Matcher m = likePattern.matcher("");
  List<SchemaResult> schemas = new ArrayList<>();
  Set<String> schemaNames = rootSchema.getSubSchemaNames();
  for(String name : schemaNames){
    m.reset(name);
    if(m.matches()){
      schemas.add(new SchemaResult(name));
    }
  }

  return schemas;
}
 
Example 18
Project: openjdk-jdk10   File: MatchProcessor.java   View source code 6 votes vote down vote up
RuleParser(String rule) {
    Matcher m = tokenizer.matcher(rule);
    List<String> list = new ArrayList<>();
    int end = 0;
    while (m.lookingAt()) {
        list.add(m.group(1));
        end = m.end();
        m.region(m.end(), m.regionEnd());
    }
    if (end != m.regionEnd()) {
        throw new RuleParseError("Unexpected tokens :" + rule.substring(m.end(), m.regionEnd()));
    }
    tokens = list.toArray(new String[0]);

    matchDescriptor = parseExpression();
    if (!done()) {
        throw new RuleParseError("didn't consume all tokens");
    }
    capturedNames.add(0, "root");
    capturedTypes.add(0, matchDescriptor.nodeType);
}
 
Example 19
Project: bibliome-java-utils   File: FormatSequence.java   View source code 6 votes vote down vote up
public FormatSequence(CharSequence in, Pattern varPat) {
	Matcher m = varPat.matcher(in);
	int last = 0;
	while (m.find()) {
		int pos = m.start();
		if (pos > last) {
			CharSequence s = in.subSequence(last, pos);
			addConstant(s);
		}
		String name = m.group(1);
		addVariable(name);
		last = m.end();
	}
	if (last < in.length()) {
		addConstant(in.subSequence(last, in.length()));
	}
}
 
Example 20
Project: Aurora   File: CharacterHandler.java   View source code 5 votes vote down vote up
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                           int dend) {

    Matcher emojiMatcher = emoji.matcher(source);
    if (emojiMatcher.find()) {
        return "";
    }

    return null;
}
 
Example 21
Project: RunicArcana   File: ModDust.java   View source code 5 votes vote down vote up
public static BlockPos parseBlockPos(Object o)
{
    if(o instanceof BlockPos)
    {
        return (BlockPos)o;
    }
    else if(o instanceof Vec3d)
    {
        return new BlockPos(((Vec3d) o).xCoord, ((Vec3d) o).yCoord, ((Vec3d) o).zCoord);
    }
    else if(o instanceof String)
    {
        Pattern p = Pattern.compile("(-?\\d+(\\.\\d)?)[ ,]+(-?\\d+(\\.\\d)?)[ ,]+(-?\\d+(\\.\\d)?)");
        Matcher m = p.matcher((String)o);
        try {
            m.find();
            int x = Integer.parseInt(m.group(1));
            int y = Integer.parseInt(m.group(3));
            int z = Integer.parseInt(m.group(5));
            return new BlockPos(x,y,z);

        }
        catch(NumberFormatException e)
        {
            return new BlockPos(0,0,0);
        }
    }
    return null;
}
 
Example 22
Project: javadoc2swagger   File: ParameterParser.java   View source code 5 votes vote down vote up
/**
 * Gets the query parameter name
 * 
 * @param paramUnformatted
 *            unformatted query parameter annotation
 * @return formatted string
 */
private String getNameFromQueryParamAnnotation(String paramUnformatted) {
    String regex = "@QueryParam\\(\"[\\w]+\"";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(paramUnformatted);
    if (matcher.find()) {
        return paramUnformatted.substring(matcher.start() + 13, matcher.end() - 1);
    }
    return null;
}
 
Example 23
Project: open-rmbt   File: ClientHandler.java   View source code 5 votes vote down vote up
/**
   * 
   * @param command
   * @param token
   * @throws IOException 
   * @throws InterruptedException 
   */
  private void runOutgoingTcpTest(String command, ClientToken token) throws Exception {
  	int port;
  	
Pattern p = Pattern.compile(QoSServiceProtocol.CMD_TCP_TEST_OUT + " ([\\d]*)");
Matcher m = p.matcher(command);
m.find();
if (m.groupCount()!=1) {
	throw new IOException("tcp outgoing test command syntax error: " + command);
}
else {
	port = Integer.parseInt(m.group(1));
}

try {
	TestServer.registerTcpCandidate(port, socket);
				
	sendCommand(QoSServiceProtocol.RESPONSE_OK, command);
}
catch (Exception e) {
	TestServerConsole.error(name + (command == null ? 
			" [No command submitted]" : " [Command: " + command + "]"), e, 1, TestServerServiceEnum.TCP_SERVICE);
}
finally {
	//is beeing done inside TcpServer now:
	//tcpServer.removeCandidate(socket.getInetAddress());
}
  }
 
Example 24
Project: yyox   File: XHSFilter.java   View source code 5 votes vote down vote up
public static Spannable spannableFilter(Context context, Spannable spannable, CharSequence text, int fontSize, EmojiDisplayListener emojiDisplayListener) {
    Matcher m = getMatcher(text);
    while (m.find()) {
        String key = m.group();
        String icon = DefXhsEmoticons.sXhsEmoticonHashMap.get(key);
        if (emojiDisplayListener == null) {
            if (!TextUtils.isEmpty(icon)) {
                emoticonDisplay(context, spannable, icon, fontSize, m.start(), m.end());
            }
        } else {
            emojiDisplayListener.onEmojiDisplay(context, spannable, icon, fontSize, m.start(), m.end());
        }
    }
    return spannable;
}
 
Example 25
Project: cstruct-parser   File: MatchUtils.java   View source code 5 votes vote down vote up
public static SimpleLengthRule matchLength(String target)
{
	List<String> ls = new ArrayList<String>();
	Pattern pattern = Pattern.compile(computerRule);
	Matcher matcher = pattern.matcher(target);
	while (matcher.find()) {
		ls.add(matcher.group());
	}
	checkLengRule(ls, target);
	return changeSimpleRuleLength(ls);
}
 
Example 26
Project: openjdk-jdk10   File: TestPLABOutput.java   View source code 5 votes vote down vote up
public static void runTest() throws Exception {
    final String[] arguments = {
        "-Xbootclasspath/a:.",
        "-XX:+UnlockExperimentalVMOptions",
        "-XX:+UnlockDiagnosticVMOptions",
        "-XX:+WhiteBoxAPI",
        "-XX:+UseG1GC",
        "-Xmx10M",
        "-Xlog:gc+plab=debug",
        GCTest.class.getName()
        };

    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(arguments);
    OutputAnalyzer output = new OutputAnalyzer(pb.start());

    output.shouldHaveExitValue(0);

    System.out.println(output.getStdout());

    String pattern = ".*GC\\(0\\) .*allocated: (\\d+).*";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(output.getStdout());

    if (!m.find()) {
        throw new RuntimeException("Could not find any PLAB statistics output");
    }
    int allocated = Integer.parseInt(m.group(1));
    assertGT(allocated, 0, "Did not allocate any memory during test");
}
 
Example 27
Project: springuni-particles   File: Validator.java   View source code 5 votes vote down vote up
/**
 * Returns <code>true</code> if the string is a valid email address.
 *
 * @param  email the string to check
 * @return <code>true</code> if the string is a valid email address;
 *         <code>false</code> otherwise
 */
public static boolean isEmail(String email) {
  if (Objects.isNull(email)) {
    return false;
  }
  Matcher matcher = EMAIL_ADDRESS_PATTERN.matcher(email);
  return matcher.matches();
}
 
Example 28
Project: sstore-soft   File: SQLLexer.java   View source code 5 votes vote down vote up
/**
 * Provide a match explanation, assuming it's a rejection.
 */
@Override
String explainMatch(Matcher matcher)
{
    String parentType = matcher.group("parenttype");
    String childType = matcher.group("childtype");
    // See if there's something to say about the parent object type.
    String explanation = getExplanation(parentType, childType != null);
    // If not see if there's something to say about the child type, when applicable.
    if (explanation == null) {
        explanation = getExplanation(childType, false);
    }
    return explanation;
}
 
Example 29
Project: dice   File: RandomOrgUtil.java   View source code 5 votes vote down vote up
/**
 * Parses the correct property from the raw response and verifies it against random.org
 * public key
 *
 * @param rawResponse the whole raw response as string
 * @param base64Sig   base64 encoded signature from the server response
 * @return true if could be verified
 */
static boolean verifySignature(String rawResponse, String base64Sig) {
    try {
        Pattern p = Pattern.compile("\"random\"\\s*:\\s*(\\{.+?})\\s*,");
        Matcher matcher = p.matcher(rawResponse);
        return matcher.find() && verifyRSA(parsePublicKey(new Base64().decode(RANDOM_ORG_PUB_KEY)), matcher.group(1).getBytes(StandardCharsets.UTF_8), new Base64().decode(base64Sig));
    } catch (Exception e) {
        throw new IllegalStateException("could not verify signature", e);
    }
}
 
Example 30
Project: AndroTickler   File: OtherUtil.java   View source code 5 votes vote down vote up
/**
 * Gets all instances that match a regex in a string
 * @param s
 * @param regex
 * @return
 */
public static boolean isRegexInString(String s, String regex){
	
	Pattern p = Pattern.compile(regex);
	Matcher m = p.matcher(s);
	if (m.matches())			
			return true;
	
	return false;
}
 
Example 31
Project: oreilly-reactive-with-akka   File: CoffeeHouseApp.java   View source code 5 votes vote down vote up
public static Map<String, String> argsToOpts(final List<String> args) {
    final Map<String, String> opts = new HashMap<>();
    for (final String arg : args) {
        final Matcher matcher = optPattern.matcher(arg);
        if (matcher.matches()) opts.put(matcher.group(1), matcher.group(2));
    }
    return opts;
}
 
Example 32
Project: incubator-netbeans   File: ShortDescriptionTest.java   View source code 5 votes vote down vote up
public void testPrintedUsage() throws Exception {
    setUpHelp();
    
    StringWriter w = new StringWriter();
    PrintWriter pw = new PrintWriter(w);

    CommandLine.getDefault().usage(pw);

    Matcher m = Pattern.compile("-h.*--help").matcher(w.toString());
    if (!m.find()) {
        fail("-h, --help should be there:\n" + w.toString());
    }

    assertEquals("No help associated", w.toString().indexOf("shorthelp"), -1);
}
 
Example 33
Project: Mobike   File: MainActivity.java   View source code 5 votes vote down vote up
private String latlng(String regexStr, String str) {
    Pattern pattern = Pattern.compile(regexStr);
    Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
        str = matcher.group(1);
    }
    return str;
}
 
Example 34
Project: jdk8u-jdk   File: OutputAnalyzer.java   View source code 5 votes vote down vote up
/**
 * Verify that the stdout contents of output buffer does not match the
 * pattern
 *
 * @param pattern
 * @throws RuntimeException
 *             If the pattern was found
 */
public OutputAnalyzer stdoutShouldNotMatch(String pattern) {
    Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(
            stdout);
    if (matcher.find()) {
        reportDiagnosticSummary();
        throw new RuntimeException("'" + pattern + "' found in stdout \n");
    }
    return this;
}
 
Example 35
Project: sealtalk-android-master   File: Regex.java   View source code 5 votes vote down vote up
public static List<String> pregMatchAll(String content, String pattern,
                                        int index) {

    List<String> matches = new ArrayList<String>();
    Matcher matcher = Pattern.compile(pattern).matcher(content);

    while (matcher.find()) {
        matches.add(TextCrawler.extendedTrim(matcher.group(index)));
    }

    return matches;
}
 
Example 36
Project: avaire   File: ArrayUtil.java   View source code 5 votes vote down vote up
public static String[] toArguments(String string) {
    List<String> arguments = new ArrayList<>();

    Matcher matcher = argumentsRegEX.matcher(string);
    while (matcher.find()) {
        arguments.add(matcher.group(0)
            .replaceAll("\"", "")
            .trim());
    }

    return arguments.toArray(new String[0]);
}
 
Example 37
Project: tableschema-java   File: TypeInferrer.java   View source code 5 votes vote down vote up
public DateTime castDatetime(String format, String value, Map<String, Object> options) throws TypeInferringException{

     Pattern pattern = Pattern.compile(REGEX_DATETIME);
     Matcher matcher = pattern.matcher(value);
     
     if(matcher.matches()){
         DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
         DateTime dt = formatter.parseDateTime(value);
         
         return dt;
         
     }else{
         throw new TypeInferringException();
     }  
 }
 
Example 38
Project: NICON   File: FuncionarioBean.java   View source code 5 votes vote down vote up
public void validarEmail()
{
    Pattern p = Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@([\\w-]+\\.)+[a-zA-Z]{2,7}$"); 
 
    if(funcionarioDados.getEmail() != null && !funcionarioDados.getEmail().equals(""))
    {
         Matcher m = p.matcher(funcionarioDados.getEmail()); 
        if (!m.find())
        {
            validoEmail = false;
            Mensagem.addErrorMsg("Email inválido");
            Validacao.AtualizarCompoente("formFuncSima", "funcionarioGrowl");
            RequestContext.getCurrentInstance().execute("soCor($('.fucP1Email'),'red')");
        }  
        else
        {
            validoEmail = true;
            Validacao.AtualizarCompoente("formFuncSima", "funcionarioGrowl");
            RequestContext.getCurrentInstance().execute("soCor($('.fucP1Email'),'')");
        }
    }
    else
    {
        validoEmail = true;
    }
    Validacao.AtualizarCompoente("formFuncSima", "fucP1ValideEmail");
}
 
Example 39
Project: easycms   File: StringUtil.java   View source code 5 votes vote down vote up
public static List<String> getImg(String s) {
	String regex;
	List<String> list = new ArrayList<String>();
	regex = "src=\"(.*?)\"";
	Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
	Matcher ma = pa.matcher(s);
	while (ma.find()) {
		list.add(ma.group());
	}
	return list;
}
 
Example 40
Project: BaseClient   File: ShaderOptionSwitch.java   View source code 5 votes vote down vote up
public static ShaderOption parseOption(String line, String path)
{
    Matcher matcher = PATTERN_DEFINE.matcher(line);

    if (!matcher.matches())
    {
        return null;
    }
    else
    {
        String s = matcher.group(1);
        String s1 = matcher.group(2);
        String s2 = matcher.group(3);

        if (s1 != null && s1.length() > 0)
        {
            boolean flag = Config.equals(s, "//");
            boolean flag1 = !flag;
            path = StrUtils.removePrefix(path, "/shaders/");
            ShaderOption shaderoption = new ShaderOptionSwitch(s1, s2, String.valueOf(flag1), path);
            return shaderoption;
        }
        else
        {
            return null;
        }
    }
}