Java Code Examples for java.util.regex.Matcher#toMatchResult()

The following examples show how to use java.util.regex.Matcher#toMatchResult() . 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 File: SqlFunctionUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a string extracted with a specified regular expression and a regex match group index.
 */
public static String regexpExtract(String str, String regex, int extractIndex) {
	if (str == null || regex == null) {
		return null;
	}

	try {
		Matcher m = Pattern.compile(regex).matcher(str);
		if (m.find()) {
			MatchResult mr = m.toMatchResult();
			return mr.group(extractIndex);
		}
	} catch (Exception e) {
		LOG.error(
			String.format("Exception in regexpExtract('%s', '%s', '%d')", str, regex, extractIndex),
			e);
	}

	return null;
}
 
Example 2
Source File: CallbackMatcher.java    From EDDI with Apache License 2.0 6 votes vote down vote up
public String replaceMatches(CharSequence charSequence, Callback callback) throws CallbackMatcherException {
    StringBuilder result = new StringBuilder(charSequence);
    final Matcher matcher = this.pattern.matcher(charSequence);
    int offset = 0;

    while (matcher.find()) {
        final MatchResult matchResult = matcher.toMatchResult();
        final String replacement = callback.foundMatch(matchResult);
        if (replacement == null) {
            continue;
        }

        int matchStart = offset + matchResult.start();
        int matchEnd = offset + matchResult.end();

        result.replace(matchStart, matchEnd, replacement);

        int matchLength = matchResult.end() - matchResult.start();
        int lengthChange = replacement.length() - matchLength;

        offset += lengthChange;
    }

    return result.toString();
}
 
Example 3
Source File: Strings.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
/**
 * 引数の文字列をラクダ記法(単語区切りが大文字)とみなして、
 * それを全て大文字のスネーク記法(単語区切りがアンダースコア)に変換します。
 * 例えば、ラクダ記法の<code>tigerSupportApi</code>は、
 * スネーク記法の<code>TIGER_SUPPORT_API</code>に変換されます。
 * @param camel ラクダ記法の文字列
 * @return スネーク記法(全て大文字)
 */
public static String toSnake(String camel) {
    if (Strings.isBlank(camel))
        return "";

    ArrayList<String> words = new ArrayList<String>();

    Matcher matcher = SNAKE_CASE_WORD.matcher(camel);
    while(matcher.find()) {
        MatchResult result = matcher.toMatchResult();
        String word = camel.substring(result.start(), result.end());

        words.add(word.toUpperCase());
    }
    return Strings.joinBy("_", words);
}
 
Example 4
Source File: StringFunctions.java    From Alink with Apache License 2.0 6 votes vote down vote up
public static String regexpExtract(String str, String regex, int extractIndex) {
    if (str == null || regex == null) {
        return null;
    }

    try {
        Matcher m = Pattern.compile(regex).matcher(str);
        if (m.find()) {
            MatchResult mr = m.toMatchResult();
            return mr.group(extractIndex);
        }
    } catch (Exception e) {
    }

    return null;
}
 
Example 5
Source File: FormatterPreviewUtils.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Do a content substitution by looking at the array size and looking for {0}...{n} strings and replace them with
 * the array's content.<br>
 * (Note - we use this method and not the NLS.bind() because it does not handle well code blocks existence)
 * 
 * @param content
 * @param substitutions
 * @return A string, substituted with the array's content.
 */
private static String substitute(String content, String[] substitutions)
{
	StringBuilder buffer = new StringBuilder(content);
	Matcher matcher = SUBSTITUTION_PATTERN.matcher(content);
	int offset = 0;
	while (matcher.find())
	{
		MatchResult matchResult = matcher.toMatchResult();
		int beginIndex = matchResult.start();
		int endIndex = matchResult.end();
		int index = Integer.parseInt(content.substring(beginIndex + 1, endIndex - 1));
		if (index >= 0 && index < substitutions.length)
		{
			String replacement = substitutions[index];
			int matchLength = endIndex - beginIndex;
			buffer.replace(offset + beginIndex, offset + endIndex, replacement);
			offset += (replacement.length() - matchLength);
		}
	}
	return buffer.toString();
}
 
Example 6
Source File: DustAnnotator.java    From Intellij-Dust with MIT License 6 votes vote down vote up
@Override
public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
  if (element instanceof DustOpenTag) {
    DustOpenTag openTag = (DustOpenTag) element;
    checkMatchingCloseTag(openTag, holder);
  }

  if (element.getNode().getElementType() == DustTypes.COMMENT) {
    String commentStr = element.getText();

    if (commentStr.length() >= 8) {
      commentStr = commentStr.substring(0, commentStr.length() - 2);
      Pattern p = Pattern.compile("TODO[^\n]*");
      Matcher m = p.matcher(commentStr);

      int startOffset = element.getTextRange().getStartOffset();
      while (m.find()) {
        MatchResult mr = m.toMatchResult();
        TextRange tr = new TextRange(startOffset + mr.start(), startOffset + mr.end());
        holder.createInfoAnnotation(tr, null).setTextAttributes(DustSyntaxHighlighter.TODO);
      }
    }
  }
}
 
Example 7
Source File: DownloadFileInfo.java    From springreplugin with Apache License 2.0 6 votes vote down vote up
/**
 * 根据文件名得到插件名
 *
 * @param fullname
 * @param type
 * @return
 */
public static final String parseName(String fullname, int type) {
    Matcher m = null;
    if (type == INCREMENT_PLUGIN) {
        m = INCREMENT_REGEX.matcher(fullname);
    } else if (type == SINGLE_PLUGIN) {
        m = INCREMENT_SINGLE_REGEX.matcher(fullname);
    } else if (type == MULTI_PLUGIN) {
        m = MULTI_REGEX.matcher(fullname);
    } else {
        m = NORMAL_REGEX.matcher(fullname);
    }
    if (m == null || !m.matches()) {
        return null;
    }
    MatchResult r = m.toMatchResult();
    if (r == null || r.groupCount() != 1) {
        return null;
    }
    return r.group(1);
}
 
Example 8
Source File: LiteralStringParser.java    From AILibs with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Literal convertStringToLiteralWithConst(final String literalString, final Set<String> evaluablePredicates) {
	String string = literalString.replace(" ", "");
	string = string.trim();

	Matcher matcher = basicPattern.matcher(string);
	if (!matcher.find()) {
		return null;
	}
	MatchResult results = matcher.toMatchResult();
	String predicateName = results.group(2); // position 2 is predicate name
	String[] paramsAsStrings = results.group(3).split(","); // position 3 are the variables
	List<LiteralParam> params = new LinkedList<>();
	for (int i = 0; i < paramsAsStrings.length; i++) {
		String param = paramsAsStrings[i].trim();
		params.add(param.startsWith("'") ? new ConstantParam(param.replace("'", "")) : new VariableParam(param));
	}

	/* try to match suffix of predicate name */
	if (evaluablePredicates.contains(predicateName)) {
		return new InterpretedLiteral(predicateName, params, results.group(1) == null);
	} else {
		return new Literal(predicateName, params, results.group(1) == null);
	}
}
 
Example 9
Source File: UsageCreator.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public String replaceVariables(String raw) throws Exception {
    if (raw == null) {
        return null;
    }

    Matcher matcher = PATTERN.matcher(raw);
    StringBuilder replaced = new StringBuilder();

    int cur = 0;

    while (matcher.find()) {
        MatchResult result = matcher.toMatchResult();

        replaced.append(raw.substring(cur, result.start(1)));

        String name = result.group(2);
        Object value = this.supplier.valueOf(name);
        if (value == null) {
            value = "${" + name + "}";
        }
        replaced.append(value);

        cur = result.end();
    }

    replaced.append(raw.substring(cur));

    return replaced.toString();
}
 
Example 10
Source File: FindReplaceDialog.java    From nextreports-designer with Apache License 2.0 5 votes vote down vote up
private MatchResult getMatchResult(Matcher matcher, boolean onlyFirst) {
    MatchResult matchResult = null;
    while (matcher.find()) {
        matchResult = matcher.toMatchResult();
        if (onlyFirst) {
        	break;
        }
    }
    
    return matchResult;
}
 
Example 11
Source File: ResourceResolvingStubDownloader.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
String relativePathPicker(Resource resource, Pattern groupAndArtifactPattern)
		throws IOException {
	Matcher groupAndArtifactMatcher = matcher(resource, groupAndArtifactPattern);
	if (groupAndArtifactMatcher.matches()
			&& groupAndArtifactMatcher.groupCount() > 2) {
		MatchResult groupAndArtifactResult = groupAndArtifactMatcher.toMatchResult();
		return groupAndArtifactResult.group(2) + groupAndArtifactResult.group(3);
	}
	else if (groupAndArtifactMatcher.matches()) {
		return groupAndArtifactMatcher.group(1);
	}
	else {
		return null;
	}
}
 
Example 12
Source File: RegexHelper.java    From PackageTemplates with Apache License 2.0 5 votes vote down vote up
public static MatchResult match(String text, String pattern) {
    Matcher matcher = Pattern.compile(pattern).matcher(text);

    if (matcher.find()) {
        return matcher.toMatchResult();
    }
    return null;
}
 
Example 13
Source File: CommentScanner.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
MatchResult find(Matcher matcher, int p) {
    try {
        if (matcher.find(p)) {
            return matcher.toMatchResult();
        }
    } catch (IndexOutOfBoundsException x) {
        // Allow p out of range, will return null as result
    }
    return null;
}
 
Example 14
Source File: PluginInfo.java    From springreplugin with Apache License 2.0 5 votes vote down vote up
public static final PluginInfo build(File f) {
    Matcher m = REGEX.matcher(f.getName());
    if (m == null || !m.matches()) {
        if (LOG) {
            LogDebug.d(PLUGIN_TAG, "PluginInfo.build: skip, no match1, file=" + f.getAbsolutePath());
        }
        return null;
    }
    MatchResult r = m.toMatchResult();
    if (r == null || r.groupCount() != 4) {
        if (LOG) {
            LogDebug.d(PLUGIN_TAG, "PluginInfo.build: skip, no match2, file=" + f.getAbsolutePath());
        }
        return null;
    }
    String name = r.group(1);
    int low = Integer.parseInt(r.group(2));
    int high = Integer.parseInt(r.group(3));
    int ver = Integer.parseInt(r.group(4));
    String path = f.getPath();
    PluginInfo info = new PluginInfo(name, low, high, ver, TYPE_PN_INSTALLED, DownloadFileInfo.NONE_PLUGIN, path, -1, -1, -1, null);
    if (LOG) {
        LogDebug.d(PLUGIN_TAG, "PluginInfo.build: found plugin, name=" + info.getName()
                + " low=" + info.getLowInterfaceApi() + " high=" + info.getHighInterfaceApi()
                + " ver=" + info.getVersion());
    }
    return info;
}
 
Example 15
Source File: Param.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public String regexRemplace(String[] regexTab, Integer i, String str){
    // Si on arrive � la fin de la cascade d'expression r�guli�re
    if(i == regexTab.length){
        // On sauvegarde la valeur que l'on remplace
        if(remplacedValue == null){
            setRemplacedValue(str);
        }
        // Si la valeur que l'on souhaite remplacer est bien la m�me
        if(remplacedValue.equals(str)){
            // On retourne le nom du param�tre
            return getName();
        }
        // Sinon
        else{
            // On ne remplace pas
            return str;
        }
    }
    
    Pattern pattern0 = Pattern.compile(regexTab[i]);
    Matcher m0 = pattern0.matcher(str);
    StringBuffer sb0 = new StringBuffer();
    while(m0.find()){
        MatchResult mr = m0.toMatchResult();
        String aRemplacer= mr.group();
        String remplacerPar = regexRemplace(regexTab, i+1, aRemplacer);
        m0.appendReplacement(sb0, remplacerPar);
    }
    m0.appendTail(sb0);
    return sb0.toString();
}
 
Example 16
Source File: PluginManager.java    From springreplugin with Apache License 2.0 4 votes vote down vote up
static final int evalPluginProcess(String name) {
    int index = IPluginManager.PROCESS_AUTO;

    try {
        if (TextUtils.equals(IPC.getPackageName(), name)) {
            if (LOG) {
                LogDebug.d(PLUGIN_TAG, "plugin process checker: default, index=" + 0);
            }
            return IPluginManager.PROCESS_UI;
        }

        if (!TextUtils.isEmpty(name)) {
            if (name.contains(PluginProcessHost.PROCESS_PLUGIN_SUFFIX2)) {
                String tail = PluginProcessHost.processTail(name);
                return PluginProcessHost.PROCESS_INT_MAP.get(tail);
            }
        }

        Matcher m = PROCESS_NAME_PATTERN.matcher(name);
        if (m == null || !m.matches()) {
            if (LOG) {
                LogDebug.d(PLUGIN_TAG, "plugin process checker: non plugin process in=" + name);
            }
            return IPluginManager.PROCESS_AUTO;
        }

        MatchResult r = m.toMatchResult();
        if (r == null || r.groupCount() != 2) {
            if (LOG) {
                LogDebug.d(PLUGIN_TAG, "plugin process checker: no group in=" + name);
            }
            return IPluginManager.PROCESS_AUTO;
        }

        String pr = r.group(1);
        if (!TextUtils.equals(IPC.getPackageName(), pr)) {
            if (LOG) {
                LogDebug.d(PLUGIN_TAG, "plugin process checker: package name not match in=" + name);
            }
            return IPluginManager.PROCESS_AUTO;
        }

        String str = r.group(2);
        index = Integer.parseInt(str);
        if (LOG) {
            LogDebug.d(PLUGIN_TAG, "plugin process checker: index=" + index);
        }
    } catch (Throwable e) {
        if (LOG) {
            LogDebug.d(PLUGIN_TAG, e.getMessage(), e);
        }
    }

    return index;
}
 
Example 17
Source File: DownloadFileInfo.java    From springreplugin with Apache License 2.0 4 votes vote down vote up
/**
 * 通过文件名和文件类型,构建V5FileInfo对象
 *
 * @param f
 * @param type
 * @return
 */
static final DownloadFileInfo build(File f, int type) {
    Matcher m = null;
    String fullname = f.getName();
    if (type == INCREMENT_PLUGIN) {
        m = INCREMENT_REGEX.matcher(fullname);
    } else if (type == SINGLE_PLUGIN) {
        m = INCREMENT_SINGLE_REGEX.matcher(fullname);
    } else if (type == MULTI_PLUGIN) {
        m = MULTI_REGEX.matcher(fullname);
    } else {
        m = NORMAL_REGEX.matcher(fullname);
    }
    if (m == null || !m.matches()) {
        if (AppConstant.LOG_V5_FILE_SEARCH) {
            if (LOG) {
                LogDebug.d(PLUGIN_TAG, "DownloadFileInfo.build: skip, no match1, type=" + type + " file=" + f.getAbsolutePath());
            }
        }
        return null;
    }
    MatchResult r = m.toMatchResult();
    if (r == null || r.groupCount() != 1) {
        if (AppConstant.LOG_V5_FILE_SEARCH) {
            if (LOG) {
                LogDebug.d(PLUGIN_TAG, "DownloadFileInfo.build: skip, no match2, type=" + type + " file=" + f.getAbsolutePath());
            }
        }
        return null;
    }
    if (!f.exists() || !f.isFile()) {
        if (AppConstant.LOG_V5_FILE_SEARCH) {
            if (LOG) {
                LogDebug.d(PLUGIN_TAG, "DownloadFileInfo.build: nor exist or file, file=" + f.getAbsolutePath());
            }
        }
        return null;
    }
    DownloadFileInfo p = new DownloadFileInfo();
    p.mName = r.group(1);
    p.mFile = f;
    p.mType = type;
    if (LOG) {
        LogDebug.d(PLUGIN_TAG, "DownloadFileInfo.build: found plugin, name=" + p.mName + " file=" + f.getAbsolutePath());
    }
    return p;
}
 
Example 18
Source File: StopWatchParser.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public MatchResult match(String message) {
   Matcher matcher = this.getPattern().matcher(message);
   return matcher.find() ? matcher.toMatchResult() : null;
}
 
Example 19
Source File: SwaggerWebAppDeploymentProducer.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Produces
public Archive swaggerWebApp() throws ModuleLoadException, IOException {

    // Load the swagger-ui webjars.
    Module module = Module.getBootModuleLoader().loadModule("org.webjars.swagger-ui");
    URL resource = module.getExportedResource("swagger-ui.jar");
    JARArchive webJar = ShrinkWrap.create(JARArchive.class);
    webJar.as(ZipImporter.class).importFrom(resource.openStream());


    JARArchive relocatedJar = ShrinkWrap.create(JARArchive.class);

    Map<ArchivePath, Node> content = webJar.getContent();

    // relocate out the webjars/swagger-ui/${VERISON}

    for (ArchivePath path : content.keySet()) {
        Node node = content.get(path);
        Asset asset = node.getAsset();
        if (asset != null) {
            Matcher matcher = PATTERN.matcher(path.get());
            if (matcher.matches()) {
                MatchResult result = matcher.toMatchResult();
                String newPath = "/META-INF/resources/" + result.group(2);
                relocatedJar.add(asset, newPath);
            }
        }
    }

    WARArchive war = ShrinkWrap.create(WARArchive.class, "swagger-ui.war")
            .addAsLibrary(relocatedJar)
            .setContextRoot(this.fraction.getContext());
    war.addClass(SwaggerDefaultUrlChangerServlet.class);

    // If any user content has been provided, merge that with the swagger-ui bits
    Archive<?> userContent = this.fraction.getWebContent();
    if (userContent != null) {
        war.merge(userContent);
    }

    return war;
}
 
Example 20
Source File: FindAddress.java    From android_9.0.0_r45 with Apache License 2.0 2 votes vote down vote up
/**
 * Attempt to match a US state beginnning at position offset in
 * content.  The matching state must be followed by a word
 * delimiter or the end of the string, and if offset is non-zero,
 * then it must also be preceded by a word delimiter.
 *
 * @return a MatchResult if a valid US state (or two letter code)
 * was found.
 */
private static MatchResult matchState(String content, int offset) {
    if (offset > 0 && WORD_DELIM.indexOf(content.charAt(offset - 1)) == -1) return null;
    Matcher stateMatcher = sStateRe.matcher(content).region(offset, content.length());
    return stateMatcher.lookingAt() ? stateMatcher.toMatchResult() : null;
}