Regexp - find numbers in a string in any order

I need to find a regular expression that allows me to find strings in which I have all the necessary numbers, but only once.

For example:

a <- c("12","13","112","123","113","1123","23","212","223","213","2123","312","323","313","3123","1223","1213","12123","2313","23123","13123")

I want to receive:

"123" "213" "312"

Sample 123 only once and in any order and in any position of the line

I tried a lot of things and it seemed closer while it is still very far from what I want:

grep('[1:3][1:3][1:3]', a, value=TRUE)
[1] "113"   "313"   "2313"  "13123"
+4
source share
2 answers

I only need to find all 3-digit numbers containing 1 2 and 3 digits

Then you can use safely

grep('^[123]{3}$', a, value=TRUE)
##=> [1] "112" "123" "113" "212" "223" "213" "312" "323" "313"

The regular expression matches:

  • ^ - beginning of line
  • [123]{3}- Exactly 3 characters that are either 1, or 2or3
  • $ - approve the position at the end of the line.

, , unique.

, Perl:

grep('^(?!.*(.).*\\1)[123]{3}$', a, value=TRUE, perl=T)
## => [1] "123" "213" "312"

. (?!.*(.).*\\1) , (.) , . , . IDEONE.

(?!.*(.).*\\1) . - regex, true, , false. , "" , "" , . (^). , regex .* ( , , 0 ), 1 (.) 1, 0 .*, 1 \\1. , 121, , look-forward false, 1 s.

+8

grep('^([123])((?!\\1)\\d)(?!\\2|\\1)\\d', a, value=TRUE, perl=T)

.

+1

Source: https://habr.com/ru/post/1609785/


All Articles