简体   繁体   English

Java字符串匹配表达式String Array

[英]Java string matching expression String Array

I am using Java, i need your opinion on how to write better code for the following task. 我正在使用Java,我需要您如何为以下任务编写更好的代码的意见。

I have following String value 我有以下字符串值

String testStr = "INCLUDES(ABC) EXCLUDES(ABC) EXCLUDES(ABC) INCLUDES(ABC) INCLUDES(ABC)"

I want to manipulate Strings and want to combine all INCLUDES statements into one INCLUDES and the result should be similar to the following: 我想操作字符串,并希望将所有INCLUDES语句合并为一个INCLUDES,其结果应类似于以下内容:

INCLUDES(ABC,ABC, ABC) EXCLUDES(ABC, ABC)

i would break the initial string into new strings using this class: http://docs.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html and put them in an array 我会使用此类将初始字符串分解为新字符串: http : //docs.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html并将它们放入数组中

start a new string, and then use the tokenizer to break out the part within the parentheses (you can set it to use ( and ) as delimiters) and loop through the array and concatenate them into the new string. 开始一个新的字符串,然后使用分词器将括号内的部分分开(您可以将其设置为使用(和)作为定界符)并遍历数组并将它们连接成新的字符串。

be aware though that any wrongly placed spaces (like INCLUDES( abc )) will mess it up 请注意,尽管任何放置错误的空格(例如INCLUDES(abc))都会使它弄乱

This seems like a reasonable approach: 这似乎是一种合理的方法:

  1. Split the testStr using the StringUtils.split method; 使用StringUtils.split方法拆分testStr use " " or null as the token. 使用“”或null作为标记。
  2. Create a Map<String, List<String>> . 创建一个Map<String, List<String>> I will refer to that as theMap 我将其称为theMap
  3. For each string in the returned array perform the following: 对于返回数组中的每个字符串,请执行以下操作:

    1. Split the string using "()" as the token. 使用“()”作为标记分割字符串。
    2. The returned array should have 2 elements. 返回的数组应包含2个元素。 The first element (index 0) is key for theMap and the second element (index 1) is the value to add to the list. 第一个元素(索引0)是theMap键,第二个元素(索引1)是要添加到列表的值。

Once you are done with the array returned from splitting testStr , build a new string by using the key value in theMap and appending the elements from the associated list into a string. 一旦你从分裂返回的数组做testStr ,通过使用键值建立一个新的字符串theMap和附加从相关列表中的元素转换为字符串。

Apache StringUtils Apache StringUtils

I wrote a piece of code for this issue but i don't know if it's good or not 我为此问题写了一段代码,但我不知道这是否好

  • according to your format ,you can split testStr by using " " ,the output will be like this: INCLUDES(ABC) 根据您的格式,您可以使用“”分割testStr ,输出将如下所示: INCLUDES(ABC)

  • check if this string contain INCLUDES or EXCLUDES 检查此字符串是否包含INCLUDESEXCLUDES

  • then split it by using ( ) 然后使用()将其拆分

Like this : 像这样 :

    String testStr = "INCLUDES(ABC) EXCLUDES(C) EXCLUDES(ABC) INCLUDES(AC) INCLUDES(AB)";
    String s[] = testStr.split(" ");
    String INCLUDES = "INCLUDES( ";
    String EXCLUDES = "EXCLUDES ( ";
    for (int i = 0; i < s.length; i++) {
        if (s[i].contains("INCLUDES")) {
            INCLUDES += (s[i].substring(s[i].indexOf("(") + 1, s[i].indexOf(")"))) + "  ";
        }

        else if (s[i].contains("EXCLUDES")) {
            EXCLUDES += (s[i].substring(s[i].indexOf("(") + 1, s[i].indexOf(")"))) + "  ";
        }
    }
    INCLUDES = INCLUDES + ")";
    EXCLUDES = EXCLUDES + ")";
    System.out.println(INCLUDES);
    System.out.println(EXCLUDES);

I have wrote down small utility result as following 我写下了以下小实用程序结果

if text = "EXCLUDES(ABC) EXCLUDES(ABC) INCLUDES(BMG) INCLUDES(EFG) INCLUDES(IJK)";

output = EXCLUDES(ABC) EXCLUDES(ABC) INCLUDES(BMG & EFG & IJK)

Following is my java codeas following please take a look and if any one can improve it please feel free. 以下是我的java代码,请看下面,如果有人可以改进它,请随意。

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sun.xml.internal.ws.util.StringUtils;

/**
 * Created by IntelliJ IDEA.
 * User: fkhan
 * Date: Aug 31, 2012
 * Time: 1:36:45 PM
 * To change this template use File | Settings | File Templates.
 */


public class TestClass {


    public static void main(String args[]) throws Exception {

        //String text = "INCLUDES(ABC) EXCLUDES(ABC) EXCLUDES(ABC) INCLUDES(EFG) INCLUDES(IJK)";
        String text = "EXCLUDES(ABC) EXCLUDES(ABC) INCLUDES(BMG) INCLUDES(EFG) INCLUDES(IJK)";
        List<String> matchedList = findMatchPhrase("INCLUDES", text);
        String query = combinePhrase(text, "INCLUDES", matchedList);
        System.out.println(query);


    }

    /**
     * This method takes query combine and & multiple phrases
     * @param expression
     * @param keyword
     * @param matchedItemList
     * @return
     */
    private static String combinePhrase(String expression, String keyword, List<String> matchedItemList) {

        //if only one phrase found return value
        if(matchedItemList.isEmpty() || matchedItemList.size() ==1){
            return expression;
        }

        //do not remove first match
        String matchedItem = null;
        for (int index = 1; index < matchedItemList.size(); index++) {

            matchedItem = matchedItemList.get(index);

            //remove match items from string other then first match
            expression = expression.replace(matchedItem, "");
        }

        StringBuffer textBuffer = new StringBuffer(expression);

        //combine other matched strings in first matched item
        StringBuffer combineStrBuf = new StringBuffer();
        if (matchedItemList.size() > 1) {

            for (int index = 1; index < matchedItemList.size(); index++) {
                String str = matchedItemList.get(index);
                combineStrBuf.append((parseValue(keyword, str)));
                combineStrBuf.append(" & ");

            }
            combineStrBuf.delete(combineStrBuf.lastIndexOf(" & "), combineStrBuf.length());
        }

        // Inject created phrase into first phrase
        //append in existing phrase
        return injectInPhrase(keyword, textBuffer, combineStrBuf.toString());
    }

    /**
     *
     * @param keyword
     * @param textBuffer
     * @param injectStr
     */
    private static String injectInPhrase(String keyword, StringBuffer textBuffer, String injectStr) {
        Matcher matcher = getMatcher(textBuffer.toString());
        while (matcher.find()) {

            String subStr = matcher.group();
            if (subStr.startsWith(keyword)) {
                textBuffer.insert(matcher.end()-1, " & ".concat(injectStr));
                break;
            }

        }

       return textBuffer.toString();
    }

    /**
     * @param expression
     * @param keyword
     * @return
     */
    private static String parseValue(String keyword, String expression) {

        String parsStr = "";
        if (expression.indexOf(keyword) > -1) {
            parsStr = expression.replace(keyword, "").replace("(", "").replace(")", "");
        }

        return parsStr;
    }


    /**
     * This method creates matcher object
     * and return for further processing
     * @param expression
     * @return
     */
    private static Matcher getMatcher(String expression){
        String patternString = "(\\w+)\\((.*?)\\)";
        Pattern pattern = Pattern.compile(patternString);
        return pattern.matcher(expression);
    }
    /**
     * This method find find matched items by keyword
     * and return as list
     * @param keyword
     * @param expression
     * @return
     */
    private static List<String> findMatchPhrase(String keyword, String expression) {
        List<String> matchList = new ArrayList<String>(3);

        keyword = StringUtils.capitalize(keyword);
        Matcher matcher = getMatcher(expression);

        while (matcher.find()) {

            String subStr = matcher.group();
            if (subStr.startsWith(keyword)) {
                matchList.add(subStr);
            }
        }

        return matchList;
    }



}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM