0

Let say I have a pattern like -

Str = "#sometext_any_character_including_&**(_etc_blabla\\s"

Now I want to replace above text with

"#some\\s"

i.e. I just want to retain first 4 characters and trailing space and beginning #. Is there any r way to do this?

Any pointer will be highly appreciated.

Bogaso
  • 2,838
  • 3
  • 24
  • 54

3 Answers3

0

I would extract using regex. If you want all text following the \\s I would capture them with an ex:

import re

# Extract
pattern = re.compile("(#[a-z]{4}|\\\s)")
my_match = "".join(pattern.findall(my_string))
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
0

An option with sub

sub("^(#.{4}).*(\\\\s)$", "\\1\\2", Str)
#[1] "#some\\s"
akrun
  • 874,273
  • 37
  • 540
  • 662
-1

str_replace(string, pattern, replacement)

or

str_replace_all(string, pattern, replacement)

You can use

  • I could use them, but in my case the replacement word is actually variable which is first few characters of supplied string – Bogaso May 27 '20 at 16:42
  • So you can use this for this. substr(Str, start = 1, stop = 3) <- "writeforreplacement" – baysal celik May 27 '20 at 17:07