【问题标题】:sub string of similar string like structure类似字符串结构的子字符串
【发布时间】:2020-06-21 09:47:00
【问题描述】:

我正在尝试编写一个 java 代码,我可以在其中获取类似结构的相同字符串的子字符串。

  1. Ex1:"Can someone help JAVA_example1_Home or JAVA_example2_Home"

  2. Ex2:"Need one more help for JAVA_example3_Home"

如您所见,JAVA_(name)_Home 很常见,但只有名称在更改。

我需要提取所有子字符串名称,如

  1. Ex1: 输出--> example1 ,example2
  2. Ex2:输出-->例子3

【问题讨论】:

  • 你可以使用正则表达式。
  • Pranjal,如果答案对您有用,通常会接受。我看到你是新来的。..

标签: java regex string collections subquery


【解决方案1】:
import java.util.regex.Matcher;  
import java.util.regex.Pattern; 
import static java.lang.System.out;
class Playground {
    public static void main(String[ ] args) {
         String [] testStrings = 
         {"Can someone help JAVA_example1_Home or JAVA_example2_Home",
          "Need one more help for JAVA_example3_Home"
         };
         Pattern pattern = Pattern.compile("(?<=JAVA_)(?<name>.*?)(?=_Home)"); 
         for (String s : testStrings) {
            out.println("Test String: " + s);
            Matcher matcher = pattern.matcher(s);
            while (matcher.find()) {
                out.println("matched: " + matcher.group("name"));
            }
            out.println("===");
         }
  
    }
}

输出:

Test String: Can someone help JAVA_example1_Home or JAVA_example2_Home
matched: example1
matched: example2
===
Test String: Need one more help for JAVA_example3_Home
matched: example3
===

解释:

  • (?&lt;=JAVA_) : 积极的向后看
  • (?&lt;name&gt;.*?) :具有非贪婪扩展的命名捕获组 .*?
  • (?=_Home) : 积极前瞻

正则表达式 101 链接:

https://regex101.com/r/A3rzf1/2

【讨论】:

    【解决方案2】:
    public static void main(String[] args) {
    
        String s1 = "Can someone help JAVA_example1_Home or JAVA_example2_Home";
        String s2 = "Need one more help for JAVA_example3_Home";
        String s3 = "I don't need help";
    
        Map.Entry<String, List<String>> r1 = extractNameHome(s1);
        Map.Entry<String, List<String>> r2 = extractNameHome(s2);
        Map.Entry<String, List<String>> r3 = extractNameHome(s3);
    
        System.out.println(r1.getKey() + " -> " + r1.getValue().toString());
        System.out.println(r2.getKey() + " -> " + r2.getValue().toString());
        System.out.println(r3.getKey() + " -> " + r3.getValue().toString());
    
    }
    
    public static Map.Entry<String, List<String>> extractNameHome(String sentence){
    
        Map.Entry<String, List<String>> result = Map.entry(sentence, new ArrayList<>());
    
        Pattern pattern = Pattern.compile("(?:JAVA_)(?<name>.+?)(?:_Home)");
        Matcher matcher = pattern.matcher(sentence);
    
        while(matcher.find()){
    
            result.getValue().add(matcher.group("name"));
    
        }
    
        return result;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 2023-03-27
      • 2014-10-02
      相关资源
      最近更新 更多