简体   繁体   English

获取多次出现的子字符串?

[英]Obtain a substring that occurs multiple times?

String str="The colors are [blue], [yellow], and [green]";

I have seen many posts how to achieve this using regex.我看过很多帖子如何使用正则表达式来实现这一点。

Here is my for loop that keeps giving me a string out of range error:
   for (int i=0;i<str.length();i++){
      String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
      System.out.println(result);

I would say you want something like that if you strictely don't want to use regex... for whatever reason.我会说你想要这样的东西,如果你严格不想使用正则表达式......无论出于何种原因。 Regex will almost certainely be equally fast and the code looks much much nicer.正则表达式几乎肯定会同样快,并且代码看起来要好得多。 But anyway here's a sample code how it would look like:但无论如何,这里有一个示例代码,它看起来像:

String str="The colors are [blue], [yellow], and [green]";

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

for(int i = str.indexOf('[', 0); i != -1; i = str.indexOf('[', i + 1)) {
    arr.add(str.substring(i + 1, str.indexOf(']', i)));
}

for(String s : arr) {
    System.out.println(s);
}

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

相关问题 StackOverflowError发生多次 - StackOverflowError occurs multiple times 返回查询作为src的子字符串出现的次数 - Return the number of times query occurs as a substring of src 如何替换仅出现一次的子字符串,而连续两次或多次排除子字符串呢? - how can I replace substring that occurs only once while excluding substring two or more times in a row? 搜索字符串以在Java中多次查找子字符串 - Search string to find substring multiple times in Java 从字符串中多次获取子字符串 - Get a substring from string multiple times 我需要计算使用扫描仪和JFIleChooser在文件中出现子字符串的次数 - I need to count the number of times a substring occurs in a file using scanner and JFIleChooser Java Regex:从多次出现的模式中提取子字符串 - Java Regex: extract a substring from a pattern occurring multiple times 如何将5个变量的块循环到ArrayList中-块多次出现不同的值 - How to loop block of 5 variables into ArrayList - block occurs with different values multiple times 是否可以通过正则表达式替换仅在结构顶层多次出现的 json 字符串中的值? - Is it possible to replace a value in a json string that occurs multiple times only at the top level of the structure via regex? 如何检查特定字符串是否在另一个字符串中多次出现? - How can I check if a specific string occurs multiple times in an other string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM