2015-04-04 2 views

ответ

2

Использование регулярных выражений - это должно работать для вас:

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

public class RegexSquareBrackets{ 
    public static void main(String[] args) { 
     String input = "[text1] [text2] [text3] [text4] [Text5] % &/!"; 

     Pattern pattern = Pattern.compile("\\[(.*?)\\]"); 
     Matcher matcher = pattern.matcher(input); 
     ArrayList<String> output = new ArrayList<String>(); 
     while (matcher.find()) 
      output.add(matcher.group(1)); 

     //Print the items out 
     System.out.println("Found Text: " + output); 
    } 
} 

После этого у вас будут элементы: «text1», «text2», «text3», «text4», «Text5» в ​​выводе ArrayList.

+1

Спасибо, что сработал :) – user3554654

+0

Отлично! - Рад, что смог помочь :) – abagshaw

0

Вы можете использовать регулярные выражения, чтобы сделать это так:

\[(\w+)\] 

Таким образом, вы можете иметь такой код:

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

public class RegexMatches 
{ 
    public static void main(String args[]){ 

     // String to be scanned to find the pattern. 
     String line = "[text1] [text2] [text3] [text4] [Text5] % &/!"; 

     Pattern r = Pattern.compile("\\[(\\w+)\\]"); 
     List<String> tagList = new ArrayList<String>(); 

     // Now create matcher object. 
     Matcher m = r.matcher(line); 
     while (m.find()) { 
      tagList.add(m.group(1)); 
     } 

     System.out.println("Found tags: " + Arrays.toString(tagList.toArray())); 
     //Output: 
     //Found tags: [text1, text2, text3, text4, Text5] 
    } 
} 
+0

Спасибо за помощь. :) – user3554654

Смежные вопросы