如何从字符串末尾每n个字符插入一个字符

时间:2018-11-16 12:14:23

标签: r regex

我想从字符串末尾开始每五个字符插入一个冒号,最好在R中使用regex和gsub。

text <- "My Very Enthusiastic Mother Just Served Us Noodles!"

我能够使用以下命令从文本开头每隔五个字符插入一个冒号:

gsub('(.{5})', "\\1:", text, perl = T)

我为实现这一目标编写了一个优雅的函数,如下所示:

library(dplyr)
str_reverse<-function(x){
  strsplit(x,split='')[[1]] %>% rev() %>% paste(collapse = "") 
}

text2<-str_reverse(text)
text3<-gsub('(.{5})', "\\1:", text2, perl = T)
str_reverse(text3)

获得理想的结果

  

[1]“ M:y Ver:y Ent:husia:stic:Mothe:r Jus:t Ser:ved U:s Noo:dles!”

有没有办法可以使用正则表达式直接实现?

1 个答案:

答案 0 :(得分:4)

您可以使用

    # only proceed if at least one contour was found
    if len(cnts) > 0:
        # find the largest contour in the mask, then use
        # it to compute the minimum enclosing circle and
        # centroid
        c = max(cnts, key=cv2.contourArea)
        ((x, y), radius) = cv2.minEnclosingCircle(c)
        M = cv2.moments(c)
        center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

        # only proceed if the radius meets a minimum size. Correct this value for your obect's size
        if radius > 2:
            # draw the circle and centroid on the frame,
            # then update the list of tracked points
            cv2.circle(frame, (int(x), int(y)), int(radius), colors[key], 2)
            cv2.putText(frame,key + " Color Detected", (int(x-radius),int(y-radius)), cv2.FONT_HERSHEY_SIMPLEX, 0.6,colors[key],2)

        if key == "Yellow" and radius > 2:
            print("Hello from other side")
# show the frame to our screen
cv2.imshow("Frame", frame)

key = cv2.waitKey(1) & 0xFF
# if the 'q' key is pressed, stop the loop
if key == ord("q"):
    break

请参见regex demo

gsub('(?=(?:.{5})+$)', ":", text, perl = TRUE) ## => [1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!" 模式与字符串中的任何位置相匹配,后跟任意5个字符(换行符除外),直到字符串末尾都重复1次或更多次。

如果输入字符串可以包含换行符,则需要在模式的开头添加(?=(?:.{5})+$)(因为PCRE regex中的(?s)默认与换行符不匹配):

.