1

I have a vector of strings and I want to remove -es from all strings (words) ending in either -ses or -ces at the same time. The reason I want to do it at the same time and not consequitively is that sometimes it happens that after removing one ending, the other ending appears while I don't want to apply this pattern to a single word twice. I have no idea how to use two patterns at the same time, but this is the best I could:

text <- gsub("[sc]+s$", "[sc]", text)

I know the replacement is not correct, but I wonder how can I show that I want to replace it with the letter I just detected (c or s in this case). Thank you in advance.

0

2 Answers 2

3

To remove es at the end of words, that is preceded with s or c, you may use

gsub("([sc])es\\b", "\\1", text)
gsub("(?<=[sc])es\\b", "", text, perl=TRUE)

To remove them at the end of strings, you can go on using your $ anchor:

gsub("([sc])es$", "\\1", text)
gsub("(?<=[sc])es$", "", text, perl=TRUE)

The first gsub TRE pattern is ([sc])es\b: a capturing group #1 that matches either s or c, and then es is matched, and then \b makes sure the next char is not a letter, digit or _. The \1 in the replacement is the backreference to the value stored in the capturing group #1 memory buffer.

In the second example with the PCRE regex (due to perl=TRUE), (?<=[sc]) positive lookbehind is used instead of the ([sc]) capturing group. Lookbehinds are not consuming text, the text they match does not land in the match value, and thus, there is no need to restore it anyhow. The replacement is an empty string.

Sign up to request clarification or add additional context in comments.

Comments

0

Strings ending with "ces" and "ses" follow the same pattern, i.e. "*es$"

If I understand it correctly than you don't need two patterns.

Example: x = c("ces", "ses", "mes)

gsub( pattern = "*([cs])es$", replacement = "\\1", x)

[1] "c" "s" "mes"

Hope it helps.

M

1 Comment

Thanks for your answer. I want to exclude any other possibilities like -mes for example.

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.