Home > Enterprise >  Extract multiple matches using a pattern from a String
Extract multiple matches using a pattern from a String

Time:01-10

I want to extract some substrings from a bigger string using some pattern. Below is my code:

library(stringr)
str_extract_all("'abcd:3343', sdgshdg374 'rgjrkgj4252:sfsfd', wdwdw'wdwd:364:ssfd', 3434", "[''][a-zA-Z0-9]['']")

Basically, I want to match pattern like ['][anything with any length]['] and followed by ,[space]. Therefore I was expecting I should get matches as 'abcd:3343' & 'rgjrkgj4252:sfsfd' & 'wdwd:364:ssfd'. Notice that for each above cases, all substrings are followed by ,[space]

With my above code, I am getting no match.

Can you please help how to construct right pattern match for this problem?

CodePudding user response:

We may need to add : also

library(stringr)
str_extract_all("'abcd:3343', sdgshdg374 'rgjrkgj4252:sfsfd', 
       wdwdw'wdwd:364:ssfd', 3434", "'[A-Za-z0-9:# ] '")[[1]]

-output

[1] "'abcd:3343'"         "'rgjrkgj4252:sfsfd'" "'wdwd:364:ssfd'"    

Or it could be also to match the ' followed by one or more characters that are not ' ([^'] ) and the '

str_extract_all("'abcd:3343', sdgshdg374 'rgjrkgj4252:sfsfd', 
       wdwdw'wdwd:364:ssfd', 3434", "'[^'] '")[[1]]
[1] "'abcd:3343'"         "'rgjrkgj4252:sfsfd'" "'wdwd:364:ssfd'"    
  •  Tags:  
  • Related