2017-02-17 3 views
0

У меня есть строка в нижнем формате.Count & Split by regex pattern in java

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

мне нужно выполнить следующее.

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 для этого,

+0

ли вам хотите найти появление «каждого» 3-буквенного слова или просто общее количество всех трехбуквенных слов? – TheLostMind

+0

Кроме того, ваша выборка неправильная. Часть DEF не имеет 'XPS' в ней – TheLostMind

+0

Хотите найти отсутствие появления« каждого »3-буквенного слова – prabu

ответ

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 
+0

Работает так, как ожидалось. Не могли бы вы немного объяснить свое решение? – prabu

+1

@prabu - Добавлены дополнительные комментарии в ответ. – TheLostMind

+0

Я хотел бы изучить эти сложные сложные выражения. Не могли бы вы посоветовать мне несколько лучших уроков или сайтов, подходящих для новичков? – prabu

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)); 
} 

выход:

АВС: 1

ABC/35/BY/200/л

DEF: 1

DEF/307/C/110/л