如何从字符串中提取某个单词

时间:2019-06-05 05:35:56

标签: java

因此,我需要帮助来找到给定字符串中的某些单词。因此,我制作了一个字符串,并使用了for循环来获取我想要的单词,但它似乎没有用,我只想从字符串中获取2019

public void wStart() throws Exception {
    String folder = "file/print/system/2019/12 - December";
    String[] folderSplit = folder.split("/");
    for (int i=3; i < folderSplit.length; i++) {
        String folderResult = folderSplit[i];
        System.out.println(folderResult);
    }
}

3 个答案:

答案 0 :(得分:5)

如果我们只希望在没有其他四位数字的字符串中获取年份,则只需使用以下表达式:

(\d{4})

Demo 1

否则我们将添加其他边界,例如:

\/(\d{4})\/ 

Demo 2

测试

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

final String regex = "(\\d{4})";
final String string = "file/print/system/2019/12 - December";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

RegEx电路

jex.im可视化正则表达式:

enter image description here

答案 1 :(得分:3)

如果年份始终是倒数第二个路径元素,则只需访问该元素:

String folder = "file/print/system/2019/12 - December";
String[] parts = folder.split("/");
String year = parts[parts.length-2];

如果相反,年份可以是任何路径元素,那么我们可以尝试将其捞出来:

String year = folder.replaceAll(".*\\b(\\d{4})\\b.*", "$1");

答案 2 :(得分:0)

您可以尝试此方法,我刚刚添加了一条语句,该语句将循环值与字符串进行比较:

public static void wStart() throws Exception
{
 String folder = "file/print/system/2019/12 - December";
  String[] folderSplit = folder.split("/");
  for(int i = 3; i < folderSplit.length; i++)
   {
      if(folderSplit[i] == "2019"){
          String folderResult = folderSplit[i];
          System.out.println("Excepted "+folderResult);
      }else{
          String folderResult = folderSplit[i];
          System.out.println("Not Excepted "+folderResult);
      }

   }
}