Akshay Shinde
Akshay Shinde

Reputation: 95

How to parse an entire line by comparing it with enum value?

I have an input string from the file as follows:

Hey_world__Welcome::To the java
Hello::World

and the enum as follows:

public enum Enum {
   Hey_world, Hello
}

I have to compare the enum value in the string and if enum is present in the string, it should print that particular string only in the output.

I tried something like this:

if(Enum.valueOf((str.split("::")[0]).split("__")[0]).equals(Enum.Hey_world)) {
  System.out.println(string); //should return string(Hey_world__Welcome::To the java)
}
else if(Enum.valueOf(str.split("::")[0]).equals(Enum.Hello)){
  System.out.println(string); //should return string(Hello::World)
}

Upvotes: 0

Views: 45

Answers (1)

user4910279
user4910279

Reputation:

You can use Regex like this.

Pattern p = Pattern.compile(
    Arrays.stream(Enum.values())
        .map(e -> e.toString())
        .collect(Collectors.joining("|")));
String str1 = "Hey_world__Welcome::To the java";
String str2 = "Hello::World";
if (p.matcher(str1).find())
    System.out.println(str1);
if (p.matcher(str2).find())
    System.out.println(str2);

Upvotes: 2

Related Questions