0

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());

3 Answers 3

2

You could do

String delete = role.substring(role.indexOf("_") + 1, role.lastIndexOf("_"));
Sign up to request clarification or add additional context in comments.

1 Comment

@Flavio, use regex only as a last resort. Reimeus' solution is far better than a regular expression for your particular problem.
0

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);

3 Comments

When I'm trying to run your code i've got Exception in thread "main" java.lang.IllegalStateException: No match found.
Very well! But it works not properly when I'm typing something like that ROLE_DE__LETE_USER (wrong expression).
@Flavio, your question does not say what should happen in such a case. You've given exactly one example. If it should work in other cases, you may want to specify that in your question.
0

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.

3 Comments

Exception in thread "main" java.lang.IllegalStateException: No match found
@Flavio You need to invoke find or matches on Matcher object.
You haven't invoked any search on the matcher yet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.