Reputation: 831
I'm trying to construct a single regex that will match a list only if it contains a specific item in the list and return all other items in the list except the one that matched.
E.g.: With this list I want to match on fruit but only return apple, orange and banana:
apple, fruit, orange, banana
I'm currently trying variations of this:
\b(?:fruit)\b|[^,\s][^\,]*[^,\s]*
This is a Java regex implementation but assume that I have no access to the code that's running the actual regex.
Upvotes: 2
Views: 123
Reputation: 12448
I have prepared the following regex that works fine for any position of your element in your list.
(.*)apple(,\s)(.*)|(.*)(,\s)apple(.*)
then you have to use the following backreference to construct your result list
$1$3$4$6
of course each time you use the regex you will have to change "apple" by the element that must be removed from the list, for this purpose create a variable that stores the element that must be removed and construct the regex dynamically by concatenating the following elements:
"(.*)" + elementToBeRemoved + "(,\s)(.*)|(.*)(,\s)" + elementToBeRemoved + "(.*)"
I have tried with banana, apple, fruit and orange and it works perfectly!!!
Upvotes: 0
Reputation: 4614
Unless I'm missing something, you should be able to simply match (.*)\bfruit\b(?:, )?(.*)
and replace with \1\2
Upvotes: 1
Reputation: 521997
Regex may not be the best tool here, but loading your items into a list may work better. In the code snippet below, I convert your CSV list of items/fruits into a formal list. With that list in hand, it is easy to determine if a certain item be present. If fruit
is found, then we can return the list minus that item, otherwise null
is returned.
public List<String> getItems(String input, String match) {
String[] array = input.split(",\\s*");
List<String> list = Arrays.asList(array);
if (list.contains(match)) {
return list.remove(match);
}
else {
return null;
}
}
String fruits = "apple, fruit, orange, banana";
List<String> result = getItems(fruits, "fruit");
Upvotes: 1