简体   繁体   中英

Replace some text after a string with Regex and Gsub in R

It's a simple question, but I'm not good with Regex. (I tried many expressions without success)

I want to replace all the text (replace for nothing) after a pattern.

My pattern is something like this:

/canais/*/

My data is:

/canais/b3/conheca-o-pai-dos-indices-da-b3/
/canais/cpbs/cvm-abre-audiencia-publica-de-instruc
/canais/stocche-forbes/dividendo-controverso/

The desired result is:

/canais/b3/
/canais/cpbs/
/canais/stocche-forbes/

How can I do it with gsub?

Thanks

You may use the following sub :

x <- c("/canais/b3/conheca-o-pai-dos-indices-da-b3/","/canais/cpbs/cvm-abre-audiencia-publica-de-instruc","/canais/stocche-forbes/dividendo-controverso/")
sub("^(/canais/[^/]+/).*", "\\1", x)

See the online R demo

Details :

  • ^ - start of string
  • (/canais/[^/]+/) - Group 1 (later referred to with \\1 ) capturing:
    • /canais/ - a substring /canais/
    • [^/]+ - 1 or more chars other than /
    • / - a slash
  • .* - any 0+ chars up to the end of string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM