Java Code Examples for java.util.regex.Pattern
The following examples show how to use
java.util.regex.Pattern. These examples are extracted from open source projects.
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: android-vlc-remote Source File: MovieParser.java License: GNU General Public License v3.0 | 6 votes |
public Movie parse(String path) { Movie movie; String fileName = File.baseName(path); for(Pattern p : patternList) { Matcher m = p.matcher(fileName); if (m.find()) { movie = new Movie(); movie.setMovieName(StringUtil.formatMatch(m.group(1))); if(m.groupCount() == 4) { movie.setYear(Integer.valueOf(m.group(2))); movie.setQuality(m.group(3)); movie.setSource(VideoSources.getFormattedSource(m.group(4))); } else if(m.groupCount() == 3) { movie.setQuality(m.group(2)); movie.setSource(VideoSources.getFormattedSource(m.group(3))); } else { movie.setQuality(m.group(2)); } return movie; } } return null; }
Example 2
Source Project: Android-AutoCompleteEditText Source File: AutoCompleteEditText.java License: MIT License | 6 votes |
@Override protected void replaceText(CharSequence text){ String beforeCursor = getText().toString().substring(0, getSelectionStart()); String afterCursor = getText().toString().substring(getSelectionStart()); Pattern pattern = Pattern.compile("#\\S*"); Matcher matcher = pattern.matcher(beforeCursor); StringBuffer sb = new StringBuffer(); int matcherStart = 0; while (matcher.find()) { int curPos = getSelectionStart(); if(curPos > matcher.start() && curPos <= matcher.end()){ matcherStart = matcher.start(); matcher.appendReplacement(sb, text.toString()+" "); } } matcher.appendTail(sb); setText(sb.toString()+afterCursor); setSelection(matcherStart + text.length()+1); }
Example 3
Source Project: knox Source File: Invoker.java License: Apache License 2.0 | 6 votes |
private static String resolveValue( Properties properties, String name ) { String value = properties.getProperty( name ); Pattern pattern = Pattern.compile( ".*?(\\$\\{)(.*?)(\\}).*" ); Matcher matcher = pattern.matcher( value ); while( matcher.matches() ) { StringBuilder resolvedValue = new StringBuilder( value.length() ); resolvedValue.append( value.substring( 0, matcher.start( 1 ) ) ); String varName = matcher.group( 2 ); String varVal = properties.getProperty( varName ); if( varVal != null ) { resolvedValue.append( varVal ); } resolvedValue.append( value.substring( matcher.end( 3 ) ) ); value = resolvedValue.toString(); matcher = pattern.matcher( value ); } return value; }
Example 4
Source Project: openjdk-jdk9 Source File: MaxWarns.java License: 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 5
Source Project: zeppelin Source File: KotlinSparkInterpreter.java License: Apache License 2.0 | 6 votes |
private static List<String> sparkClasspath() { String sparkJars = System.getProperty("spark.jars"); Pattern isKotlinJar = Pattern.compile("/kotlin-[a-z]*(-.*)?\\.jar"); Stream<File> addedJars = Arrays.stream(Utils.resolveURIs(sparkJars).split(",")) .filter(s -> !s.trim().equals("")) .filter(s -> !isKotlinJar.matcher(s).find()) .map(s -> { int p = s.indexOf(':'); return new File(s.substring(p + 1)); }); Stream<File> systemJars = Arrays.stream( System.getProperty("java.class.path").split(File.pathSeparator)) .map(File::new); return Stream.concat(addedJars, systemJars) .map(file -> { try { return file.getCanonicalPath(); } catch (IOException e) { return ""; } }) .collect(Collectors.toList()); }
Example 6
Source Project: sealtalk-android Source File: CommonUtils.java License: MIT License | 6 votes |
/** * 邮箱格式是否正确 * * @param email * @return */ public static boolean isEmail(String email) { if (TextUtils.isEmpty(email)) return false; String expression = "^[\\w\\.-][email protected]([\\w\\-]+\\.)+[A-Z]{2,4}$"; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(email); if (matcher.matches()) return true; else return false; }
Example 7
Source Project: idea-php-symfony2-plugin Source File: TwigTemplateGoToDeclarationHandler.java License: MIT License | 6 votes |
/** * Extract class from inline variables * * {# @var \AppBundle\Entity\Foo variable #} * {# @var variable \AppBundle\Entity\Foo #} */ @NotNull private Collection<PhpClass> getVarClassGoto(@NotNull PsiElement psiElement) { String comment = psiElement.getText(); if(StringUtils.isBlank(comment)) { return Collections.emptyList(); } for(String pattern: TwigTypeResolveUtil.DOC_TYPE_PATTERN_SINGLE) { Matcher matcher = Pattern.compile(pattern).matcher(comment); if (matcher.find()) { String className = matcher.group("class"); if(StringUtils.isNotBlank(className)) { return PhpElementsUtil.getClassesInterface(psiElement.getProject(), className); } } } return Collections.emptyList(); }
Example 8
Source Project: jbang Source File: Script.java License: MIT License | 6 votes |
List<String> quotedStringToList(String subjectString) { List<String> matchList = new ArrayList<String>(); Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'"); Matcher regexMatcher = regex.matcher(subjectString); while (regexMatcher.find()) { if (regexMatcher.group(1) != null) { // Add double-quoted string without the quotes matchList.add(regexMatcher.group(1)); } else if (regexMatcher.group(2) != null) { // Add single-quoted string without the quotes matchList.add(regexMatcher.group(2)); } else { // Add unquoted word matchList.add(regexMatcher.group()); } } return matchList; }
Example 9
Source Project: webdsl Source File: AbstractEntitySearcher.java License: Apache License 2.0 | 6 votes |
private Query createRegexQuery ( QueryDef qd ) { BooleanQuery query = new BooleanQuery(); List<SpanQuery> spanClausesList = new ArrayList<SpanQuery>(); String[] queryStrings; SpanQuery[] spanClausesArray; RegexQuery regexQuery; for ( String fld : qd.fields ) { spanClausesList.clear(); queryStrings = qd.query.split(" "); spanClausesArray = new SpanQuery[queryStrings.length]; for ( String subquery : queryStrings ) { regexQuery = new RegexQuery( new Term( fld, subquery ) ); regexQuery.setRegexImplementation( new JavaUtilRegexCapabilities() ); //if emptyable, like a query '(optional)?' or 'bla|a*', make span optional by wrapping it SpanOrQuery if(Pattern.matches(subquery, "")){ spanClausesList.add( new SpanOrQuery( new SpanMultiTermQueryWrapper<RegexQuery>( regexQuery ) ) ); } else { spanClausesList.add( new SpanMultiTermQueryWrapper<RegexQuery>( regexQuery ) ); } } spanClausesList.toArray( spanClausesArray ); query.add( new SpanNearQuery( spanClausesArray, 0, true), Occur.SHOULD ); } return query; }
Example 10
Source Project: zom-android-matrix Source File: MessageListItem.java License: Apache License 2.0 | 6 votes |
/** * Returns a list with all links contained in the input */ public static List<String> extractUrls(String text) { List<String> containedUrls = new ArrayList<String>(); String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)"; Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE); Matcher urlMatcher = pattern.matcher(text); while (urlMatcher.find()) { containedUrls.add(text.substring(urlMatcher.start(0), urlMatcher.end(0))); } return containedUrls; }
Example 11
Source Project: openjdk-jdk9 Source File: GenerateEnumSchema.java License: GNU General Public License v2.0 | 6 votes |
@Test(dataProvider="schemagenGenerationData") public void schemangenGenerationTestCase(String shortTestName, String inputFileName, String regexp) throws IOException { //Create test case directory Path testCaseDir = testWorkDir.resolve(shortTestName); Files.createDirectories(testCaseDir); //Copy java source from test.src to the test case dir Files.copy(testSrcDir.resolve(inputFileName), testCaseDir.resolve(inputFileName), REPLACE_EXISTING); //Run schemagen runSchemaGen(inputFileName, testCaseDir); //Check if schema file generated Assert.assertTrue(Files.exists(testCaseDir.resolve(SCHEMA_FILE))); //Read schema content from file String content = Files.lines(testCaseDir.resolve(SCHEMA_FILE)).collect(Collectors.joining("")); System.out.println("Generated schema: " + content); //Check if schema contains expected content Assert.assertTrue(Pattern.matches(regexp, content)); }
Example 12
Source Project: youkefu Source File: UKTools.java License: Apache License 2.0 | 6 votes |
/** * * @param message */ public static AsrResult parseAsrResult(String id,String message , int speakms) { AsrResult asrResult = null ; Pattern pattern = Pattern.compile("([\\d]{1,})[\\.]{1}([\\s\\S]*);"); Matcher matcher = pattern.matcher(message); if(matcher.find() && matcher.groupCount() == 2) { asrResult = new AsrResult(id , matcher.group(2) , matcher.group(1)); if(asrResult.getMessage().endsWith("。")) { asrResult.setMessage(asrResult.getMessage().substring(0 , asrResult.getMessage().length() - 1)); } } if(speakms > 0 && asrResult!=null) { asrResult.setSpeakms(speakms); } return asrResult; }
Example 13
Source Project: idea-php-symfony2-plugin Source File: TwigTypeResolveUtil.java License: MIT License | 6 votes |
private static Map<String, String> getInlineCommentDocsVars(@NotNull PsiElement twigCompositeElement) { Map<String, String> variables = new HashMap<>(); for(PsiElement psiComment: YamlHelper.getChildrenFix(twigCompositeElement)) { if(!(psiComment instanceof PsiComment)) { continue; } String text = psiComment.getText(); if(StringUtils.isBlank(text)) { continue; } for (Pattern pattern : INLINE_DOC_REGEX) { Matcher matcher = pattern.matcher(text); while (matcher.find()) { variables.put(matcher.group("var"), matcher.group("class")); } } } return variables; }
Example 14
Source Project: t-io Source File: ReUtil.java License: Apache License 2.0 | 6 votes |
/** * 正则替换指定值<br> * 通过正则查找到字符串,然后把匹配到的字符串加入到replacementTemplate中,$1表示分组1的字符串 * * @param content 文本 * @param pattern {@link Pattern} * @param replacementTemplate 替换的文本模板,可以使用$1类似的变量提取正则匹配出的内容 * @return 处理后的文本 * @since 3.0.4 */ public static String replaceAll(String content, Pattern pattern, String replacementTemplate) { if (StrUtil.isEmpty(content)) { return content; } final Matcher matcher = pattern.matcher(content); boolean result = matcher.find(); if (result) { final Set<String> varNums = findAll(PatternPool.GROUP_VAR, replacementTemplate, 1, new HashSet<String>()); final StringBuffer sb = new StringBuffer(); do { String replacement = replacementTemplate; for (String var : varNums) { int group = Integer.parseInt(var); replacement = replacement.replace("$" + var, matcher.group(group)); } matcher.appendReplacement(sb, escape(replacement)); result = matcher.find(); } while (result); matcher.appendTail(sb); return sb.toString(); } return content; }
Example 15
Source Project: AOSP-Kayboard-7.1.2 Source File: BinaryDictionaryUtils.java License: Apache License 2.0 | 6 votes |
public static boolean renameDict(final File dictFile, final File newDictFile) { if (dictFile.isFile()) { return dictFile.renameTo(newDictFile); } else if (dictFile.isDirectory()) { final String dictName = dictFile.getName(); final String newDictName = newDictFile.getName(); if (newDictFile.exists()) { return false; } for (final File file : dictFile.listFiles()) { if (!file.isFile()) { continue; } final String fileName = file.getName(); final String newFileName = fileName.replaceFirst( Pattern.quote(dictName), Matcher.quoteReplacement(newDictName)); if (!file.renameTo(new File(dictFile, newFileName))) { return false; } } return dictFile.renameTo(newDictFile); } return false; }
Example 16
Source Project: docker-compose-rule Source File: IOMatchers.java License: Apache License 2.0 | 6 votes |
public static Matcher<String> matchingPattern(String patternStr) { return new TypeSafeDiagnosingMatcher<String>() { @Override protected boolean matchesSafely(String text, Description mismatchDescription) { Pattern pattern = Pattern.compile(patternStr, Pattern.DOTALL); boolean matches = pattern.matcher(text).matches(); if (!matches) { mismatchDescription.appendText(text); } return matches; } @Override public void describeTo(Description description) { description.appendText("matching '" + patternStr + "'"); } }; }
Example 17
Source Project: defense-solutions-proofs-of-concept Source File: CoTAdapter.java License: Apache License 2.0 | 6 votes |
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 18
Source Project: jsr354-ri Source File: CurrencyQueryTest.java License: Apache License 2.0 | 6 votes |
/** * Tests that searching currencies by regex is supported. */ @Test public void testSeachByRegex() { String dollarRegex = "\\p{Upper}{2}D"; Pattern dollarPattern = Pattern.compile(dollarRegex); Collection<CurrencyUnit> allCurrencies = Monetary.getCurrencies(CurrencyQueryBuilder.of().build()); Set<String> availableDollarCodes = allCurrencies.stream() .map(CurrencyUnit::getCurrencyCode) .filter(currencyCode -> dollarPattern.matcher(currencyCode).matches()) .collect(toSet()); assertFalse(availableDollarCodes.isEmpty()); CurrencyQuery dollarQuery = CurrencyQueryBuilder.of().setCurrencyCodes(dollarRegex).build(); Collection<CurrencyUnit> dollarCurrencies = Monetary.getCurrencies(dollarQuery); for (CurrencyUnit dollarCurrency : dollarCurrencies) { availableDollarCodes.remove(dollarCurrency.getCurrencyCode()); } assertTrue(availableDollarCodes.isEmpty()); }
Example 19
Source Project: LoggerPlusPlus Source File: GrepResults.java License: GNU Affero General Public License v3.0 | 6 votes |
private void processMatches(Pattern pattern, byte[] content, boolean isRequest){ final Matcher respMatcher = pattern.matcher(new String(content)); while(respMatcher.find() && !Thread.currentThread().isInterrupted()){ String[] groups = new String[respMatcher.groupCount()+1]; for (int i = 0; i < groups.length; i++) { groups[i] = respMatcher.group(i); } if(isRequest) { requestMatches++; }else { responseMatches++; } results.add(new Match(groups, isRequest)); } }
Example 20
Source Project: hawkular-metrics Source File: SimpleTagQueryParser.java License: Apache License 2.0 | 5 votes |
private Func1<String, Boolean> tagNameFilter(String regexp) { if(regexp != null) { boolean positive = (!regexp.startsWith("!")); Pattern p = PatternUtil.filterPattern(regexp); return s -> positive == p.matcher(s).matches(); // XNOR } return s -> true; }
Example 21
Source Project: Leisure Source File: Utils.java License: GNU Lesser General Public License v3.0 | 5 votes |
public static String RegexFind(String regex,String string,int start,int end){ Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(string); String res = string; while (matcher.find()){ res = matcher.group(); } return res.substring(start, res.length() - end); }
Example 22
Source Project: huaweicloud-sdk-java-obs Source File: ObsException.java License: Apache License 2.0 | 5 votes |
private String findXmlElementText(String xmlMsg, String elementName) { Pattern pattern = Pattern.compile(".*<" + elementName + ">(.*)</" + elementName + ">.*"); Matcher matcher = pattern.matcher(xmlMsg); if (matcher.matches() && matcher.groupCount() == 1) { return matcher.group(1); } else { return null; } }
Example 23
Source Project: incubator-gobblin Source File: DatasetFilterUtils.java License: Apache License 2.0 | 5 votes |
/** * A topic survives if (1) it doesn't match the blacklist, and * (2) either whitelist is empty, or it matches the whitelist. * Whitelist and blacklist use regex patterns (NOT glob patterns). */ public static boolean survived(String topic, List<Pattern> blacklist, List<Pattern> whitelist) { if (stringInPatterns(topic, blacklist)) { return false; } return (whitelist.isEmpty() || stringInPatterns(topic, whitelist)); }
Example 24
Source Project: openAGV Source File: StandardKernel.java License: Apache License 2.0 | 5 votes |
@Override @Deprecated public <T extends TCSObject<T>> Set<T> getTCSObjects(Class<T> clazz, Pattern regexp) throws CredentialsException { LOG.debug("method entry"); return kernelState.getTCSObjects(clazz, regexp); }
Example 25
Source Project: cloudml Source File: DotText.java License: GNU Lesser General Public License v3.0 | 5 votes |
public static int countOccurences(String dotText, String label) { final Pattern pattern = Pattern.compile(label, Pattern.MULTILINE); Matcher matcher = pattern.matcher(dotText); int count = 0; while (matcher.find()) { count++; } return count; }
Example 26
Source Project: openshift-elasticsearch-plugin Source File: KibanaUtils.java License: Apache License 2.0 | 5 votes |
public KibanaUtils(final PluginSettings settings, final PluginClient pluginClient) { this.pluginClient = pluginClient; this.projectPrefix = StringUtils.isNotBlank(settings.getCdmProjectPrefix()) ? settings.getCdmProjectPrefix() : ""; this.reIndexPattern = Pattern.compile("^" + projectPrefix + "\\.(?<name>[a-zA-Z0-9-]*)\\.(?<uid>.*)\\.\\*$"); this.reProjectFromIndex = Pattern.compile("^(" + projectPrefix + ")?\\.(?<name>[a-zA-Z0-9-]*)(\\.(?<uid>.*))?\\.\\d{4}\\.\\d{2}\\.\\d{2}$"); this.defaultVersion = Version.valueOf(ConfigurationSettings.DEFAULT_KIBANA_VERSION); }
Example 27
Source Project: ADT_Frontend Source File: AbapGitStagingTreeFilter.java License: MIT License | 5 votes |
private Pattern wildcardToRegex(String filter) { String trimmed = filter.trim(); if (trimmed.isEmpty()) { return null; } String regex = (trimmed.contains("*") ? "^" : "") + "\\Q"//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + trimmed.replaceAll("\\*", //$NON-NLS-1$ Matcher.quoteReplacement("\\E.*?\\Q")) //$NON-NLS-1$ + "\\E";//$NON-NLS-1$ // remove potentially empty quotes at begin or end regex = regex.replaceAll(Pattern.quote("\\Q\\E"), ""); //$NON-NLS-1$ //$NON-NLS-2$ return Pattern.compile(regex); }
Example 28
Source Project: j2objc Source File: MatcherTest.java License: Apache License 2.0 | 5 votes |
private void hitEndTest(boolean callFind, String testNo, String regex, String input, boolean hit) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); if (callFind) { matcher.find(); } else { matcher.matches(); } boolean h = matcher.hitEnd(); assertTrue(testNo, h == hit); }
Example 29
Source Project: phoebus Source File: EdmDisplayParser.java License: Eclipse Public License 1.0 | 5 votes |
/** * Parses group header data. * * @param group EdmEntity representing group. * @param groupData Group data to parse. * @param endGroupPosition Position where "endGroup" statement is. Used for parsing data between "endGroup" and "endObjectProperties" * @return Data without parsed section. * @throws EdmException if an error occurs. */ private StringBuilder parseGroupHeader(EdmEntity group, StringBuilder groupData, int endGroupPosition) throws EdmException { // group data between "endGroup" and "endObjectProperties" declaration int afterDataStart = endGroupPosition + 8; // 8 = "endGroup".length int afterDataEnd = groupData.length() - 19; // 19 = "endObjectProperties".length String afterData = groupData.substring(afterDataStart, afterDataEnd); // removes afterData from groupData groupData.delete(endGroupPosition, groupData.length()); // group data between "beginObjectProperties" and "beginGroup" declaration Pattern p = Pattern.compile( "(object\\s+activeGroupClass.*?beginObjectProperties(.*?)beginGroup)", Pattern.DOTALL); Matcher m = p.matcher(groupData); m.find(); int start = m.start(); int end = m.end(); String matchData = m.group(2); // append afterData matchData = matchData + afterData; Pattern p1 = Pattern.compile(".*"); Matcher m1 = p1.matcher(matchData); while (m1.find()) parseProperty(m1, group); groupData.delete(start, end); return groupData; }
Example 30
Source Project: uyuni Source File: MockModulemdApi.java License: GNU General Public License v2.0 | 5 votes |
/** * Creates a test channel including all the modular packages served by this mock class. * * In addition, the channel includes also the 'perl-5.26.3' package, which is part of 'perl:5.26' module definition, * but served as a regular package. * * @param user the user to create the channel with * @return a populated test channel */ public static Channel createModularTestChannel(User user) throws Exception { Channel channel = TestUtils.reload(ChannelFactoryTest.createTestChannel(user, "channel-x86_64")); channel.setChecksumType(ChannelFactory.findChecksumTypeByLabel("sha1")); Modules modulemd = new Modules(); modulemd.setChannel(channel); modulemd.setRelativeFilename("/path/to/modulemd.yaml"); channel.setModules(modulemd); List<String> nevras = doGetAllPackages(); // perl 5.26 is a special package which is included in the module definition even though it's not served as a // modular package. We need it in the channel to be able to test this case. String perlNevra = "perl-5.26.3-416.el8:4.x86_64"; nevras.add(perlNevra); // 'modularitylabel' rpm tag determines that a package belongs to a module PackageExtraTagsKeys modularityHeader = PackageManagerTest.createExtraTagKey("modularitylabel"); Pattern nevraPattern = Pattern.compile("^(.*)-(\\d+):(.*)-(.*)\\.(.*)$"); for (String nevra : nevras) { Matcher m = nevraPattern.matcher(nevra); if (m.matches()) { Package pkg = PackageTest.createTestPackage(user.getOrg()); PackageTest.populateTestPackage(pkg, user.getOrg(), PackageNameTest.createTestPackageName(m.group(1)), PackageEvrFactoryTest.createTestPackageEvr(m.group(2), m.group(3), m.group(4)), PackageFactory.lookupPackageArchByLabel(m.group(5))); if (!perlNevra.equals(nevra)) { // Exclude non-modular Perl package mentioned above pkg.setExtraTags(Collections.singletonMap(modularityHeader, "my:nsvc")); } channel.addPackage(pkg); } } ChannelFactory.save(channel); return channel; }