2

I have to replace " used as a unit of measure (inches) in strings that also contain characters in double quotes.

uuuu<- c('BELT, "V" 5L610, LONG 4.5" WIDE 7.5", TYPE "K"')

The vector in my data has 70k+ rows, I only need to worry about the " right after numbers. my desired results would be - BELT, "V" 5L610, LONG 4.5IN WIDE 7.5IN, TYPE "K"

I tried gsub('\\d\"',"\\dIN",uuuu) but you know that's not going to give me the result correct result: "BELT, \"V\" 5L610, LONG 4.dIN WIDE 7.dIN, TYPE \"K\"

Then I tried grep to find the pattern and get the indices, however, that doesn't seem to reasonable since a single string in the vector could have both " as a UOM and as a quote. grep('\\d\"',uuuu,value = FALSE)

How do I retain the digit from my pattern? It should be possible in gsub?

4
  • 3
    Maybe gsub('(\\d)"', "\\1IN", uuuu)? Commented Jan 20, 2018 at 20:39
  • @WiktorStribiżew Thank you, I have come across 1,2 before in Regex. But I was not able to find a reference where I can learn about exactly what they are? can you share a reference? If you want I'll the accept the solution if posted. Commented Jan 20, 2018 at 20:49
  • This website is one of my favorites Commented Jan 21, 2018 at 0:07
  • @Poppinyoshi See my answer below. Commented Jan 22, 2018 at 6:36

1 Answer 1

2

You may use a capturing group (a pair of unescaped parentheses) around the part of the pattern you need to keep after replacement and a backreference to the group value inside the replacement pattern:

gsub('(\\d)"', "\\1IN", uuuu)
      ^   ^     ^^^

See the regex demo.

Pattern details

  • (\d) - Capturing group 1 (whose value can be referenced to with a \1 backreference from the replacement pattern): any digit
  • " - a double quote.

R demo:

uuuu<- c('BELT, "V" 5L610, LONG 4.5" WIDE 7.5", TYPE "K"')
cat(gsub('(\\d)"', "\\1IN", uuuu))
## => BELT, "V" 5L610, LONG 4.5IN WIDE 7.5IN, TYPE "K"
Sign up to request clarification or add additional context in comments.

Comments

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.