Извлечь шаблон из текста - PullRequest
2 голосов
/ 20 апреля 2020

Я хочу извлечь какой-то шаблон, который немного сложен.

Я хочу извлечь минимум 5 и максимум 9 ди git alphanumeri c символов из текста столбца и распечатать их в новом столбце. Если они несколько я хочу сделать в формате через запятую. где все в формате через запятую.

Шаблон начинается с алфавита или цифры c, но вы не хотите, чтобы этот шаблон начинался с D или DF _.

df = data.frame(Text=c(("in which some columns are 1A265T up for some rows."),
                    ("It's too large to 12345AB MB eyeball in order to identify D12345AB"),
                    ("some data to the axis A6651F correct columns for these rows"),
                    ("Any output that would allow me to identify that AJ_DF125AA12."),
                    ("how do I find some locations 564789.")))`enter code here`  

Desired output is:

       Text                                                   Pattern

 1       in which some columns are 1A265T , SDFG123 
         up for some rows.                                      1A265T , SDFG123
 2       It's too large to 12345AB MB eyeball in order to 
         identify P12345AB                                      12345AB
 3       some data to the axis A6651F correct columns 
         for these rows                                         A6651F
 4       Any output that would allow me to identify
         that AJ_DF125AA12.                                       NA
 5       how do I find some locations 564789.                   564789  

I have use str_detect function.

df %>% 
  filter(str_detect(text, ".+[A-Z0-9,]+"))

Does anybody know the correct way??

Ответы [ 2 ]

3 голосов
/ 20 апреля 2020

Вы можете использовать

df = data.frame(Text=c(("in which some columns are 1A265T , SDFG123 up for some rows."),
                     ("It's too large to 12345AB MB eyeball in order to identify D12345AB"),
                     ("some data to the axis A6651F correct columns for these rows"),
                     ("Any output that would allow me to identify that AJ_DF125AA12."),
                     ("how do I find some locations 564789.")))

df$Pattern <- lapply(str_extract_all(df$Text, "\\b[A-CE-Z0-9][A-Z0-9]{4,8}\\b"), paste, collapse=",")
df[df==''] <- NA

Выход:

                                                            Text        Pattern
1       in which some columns are 1A265T , SDFG123 up for some rows. 1A265T,SDFG123
2 It's too large to 12345AB MB eyeball in order to identify D12345AB        12345AB
3        some data to the axis A6651F correct columns for these rows         A6651F
4      Any output that would allow me to identify that AJ_DF125AA12.             NA
5                               how do I find some locations 564789.         564789

Регулярное выражение соответствует

  • \b - граница слова
  • [A-CE-Z0-9] - цифры ASCII или заглавные буквы, отличные от D
  • [A-Z0-9]{4,8} - от четырех до восьми цифр ASCII или заглавные буквы
  • \b - граница слова.

См. Демонстрационную версию regex .

Обратите внимание, что вы можете "упростить" шаблон с помощью негативного взгляда:

\b(?!D)[A-Z0-9]{5,9}\b

См. это регулярное выражение , где (?!D) требует, чтобы следующий символ не был D.

0 голосов
/ 20 апреля 2020

в Base-R

AllNumbers <- regmatches(df$Text, gregexpr("[A-z0-9]+\\d+[A-z0-9]+", df$Text))
AllNumbers <- sapply(AllNumbers, function(x) gsub("^D[A-z0-9]+","",x) )
AllLengths <- sapply(AllNumbers, nchar)

df$Pattern <- sapply(1:length(AllNumbers), function(x)  AllNumbers[[x]][AllLengths[[x]]>=5 & AllLengths[[x]]<=9])

выход:

> df
                                                                Text Pattern
1                 in which some columns are 1A265T up for some rows.  1A265T
2 It's too large to 12345AB MB eyeball in order to identify D12345AB 12345AB
3        some data to the axis A6651F correct columns for these rows  A6651F
4      Any output that would allow me to identify that AJ_DF125AA12.        
5                               how do I find some locations 564789.  564789
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...