Flavio
Flavio

Reputation: 915

How to parse a string with regex?

How to retrive DELETE string from ROLE_DELETE_USER with reqular expression?

String role = "ROLE_DELETE_USER";
Pattern pattern = Pattern.compile("???");
Matcher matcher = pattern.matcher(role);
System.out.println(matcher.group());

Upvotes: 0

Views: 48

Answers (3)

Rogue
Rogue

Reputation: 11483

It doesn't help to have only one example of strings to parse, because you could do it in multiple ways. If you wanted to, here are a couple patterns:

[A-Z]+_(.*)_[A-Z]+
[A-Za-z]+_(.*)_[A-Za-z]+

Which would come out as:

String role = "ROLE_DELETE_USER";
Pattern pattern = Pattern.compile("[A-Z]+_(.*)_[A-Z]+");
Matcher matcher = pattern.matcher(role);
matcher.find();
System.out.println(matcher.group(1));

An alternative solution (not using regex) would to break down the roles into a string array:

String input = "ROLE_DELETE_USER";
String[] tasks = input.split("_");
//args[0] == "ROLE"
//args[1] == "DELETE"
//args[2] == "USER"

This allows a lot more flexibility imo for figuring out what you want to do with the input.

Upvotes: 0

Paul Draper
Paul Draper

Reputation: 83205

Regular expressions are meant to handle patterns. You don't have much of a pattern (just one example), but this will work in at least that one case.

String role = "ROLE_DELETE_USER";
Pattern pattern = Pattern.compile("^ROLE_(.*)_USER$");
Matcher matcher = pattern.matcher(role);
if(matcher.find()) {
    System.out.println(matcher.group(1));
}

Here, (.*) is a capture group. match.group(1) retrieves the content of the first capture group.


Of course, you could also just do

String role = "ROLE_DELETE_USER";
role = role.substring(5, role.length() - 5)
System.out.println(role);

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

You could do

String delete = role.substring(role.indexOf("_") + 1, role.lastIndexOf("_"));

Upvotes: 2

Related Questions