伯爵&在java

时间:2017-02-17 05:53:04

标签: java regex

我有一个以下格式的字符串。

  

-52 / ABC / 35 / BY / 200 / L / DEF / 307 / C / 110 / L

我需要执行以下操作。

 1. Find the no of occurrences of 3 letter word's like ABC,DEF in the above text.
 2. Split the above string by ABC and DEF as shown below. 
    ABC/35/BY/200/L
    DEF/307/C/110/L

我尝试使用带有以下代码的正则表达式,但它始终显示匹配计数为零。如何轻松解决这个问题。

static String DEST_STRING = "^[A-Z]{3}$";
    static Pattern DEST_PATTERN = Pattern.compile(DEST_STRING,
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    public static void main(String[] args) {
        String test = "-52/ABC/35/BY/200/L/DEF/307/C/110/L";
        Matcher destMatcher = DEST_PATTERN.matcher(test);
        int destCount = 0;
        while (destMatcher.find()) {
            destCount++;
        }
        System.out.println(destCount);
    }

请注意我需要使用JDK 6,

2 个答案:

答案 0 :(得分:2)

您可以使用此代码:

public static void main(String[] args) throws Exception {
    String s = "-52/ABC/35/BY/200/L/DEF/307/C/110/L";
    // Pattern to find all 3 letter words . The \\b means "word boundary", which ensures that the words are of length 3 only. 
    Pattern p = Pattern.compile("(\\b[a-zA-Z]{3}\\b)");
    Matcher m = p.matcher(s);
    Map<String, Integer> countMap = new HashMap<>();
    // COunt how many times each 3 letter word is used.
   // Find each 3 letter word.
    while (m.find()) {
        // Get the 3 letter word.
        String val = m.group();
        // If the word is present in the map, get old count and add 1, else add new entry in map and set count to 1
        if (countMap.containsKey(val)) {
            countMap.put(val, countMap.get(val) + 1);
        } else {
            countMap.put(val, 1);
        }
    }
    System.out.println(countMap);
    // Get ABC.. and DEF.. using positive lookahead for a 3 letter word or end of String 
    // Finds and selects everything starting from a 3 letter word until another 3 letter word is found or until string end is found.
    p = Pattern.compile("(\\b[a-zA-Z]{3}\\b.*?)(?=/[A-Za-z]{3}|$)");
    m = p.matcher(s);
    while (m.find()) {
        String val = m.group();
        System.out.println(val);
    }

}

O / P:

{ABC=1, DEF=1}
ABC/35/BY/200/L
DEF/307/C/110/L

答案 1 :(得分:1)

检查一下:

String stringToSearch = "-52/ABC/35/BY/200/L/DEF/307/C/110/L";
Pattern p1 = Pattern.compile("\\b[a-zA-Z]{3}\\b");
Matcher m = p1.matcher(stringToSearch);

int startIndex = -1;
while (m.find())
{
    //Try to use Apache Commons' StringUtils
    int count = StringUtils.countMatches(stringToSearch, m.group());   
    System.out.println(m.group +":"+ count);

    if(startIndex != -1){
      System.out.println(stringToSearch.substring(startIndex,m.start()-1));
    }
    startIndex = m.start(); 
}
if(startIndex != -1){
    System.out.println(stringToSearch.substring(startIndex));
}

输出:

ABC:1

ABC / 35 / BY / 200 / L

DEF:1

DEF / 307 / C / 110 / L