Find and print lines in a file that exactly match a line or regular expression (Ruby)

In ruby ​​1.9.3, I try to write a program that will find all words with n number of characters taken from an arbitrary character set. For example, if I are given the characters [b, a, h, s, v, i, e, y, k, s, a] and n = 5, I need to find all 5-letter words that can only be executed with these characters . Using the 2of4brif.txt word list from http://wordlist.sourceforge.net/ (to include British words and letters), I tried to execute the following code:

a = %w[b a h s v i e y k s a]
a.permutation(5).map(&:join).each do |x|
  File.open('2of4brif.txt').each_line do |line|
    puts line if line.match(/^[#{x}]+$/)
  end
end

It does nothing (no error message, no output, as if it were frozen). I also tried changing the options based on the following threads:

What is the best way to find a string in a file?

Ruby will find the line in the file and the print result

How to find the exact match string in a text file using Ruby?

Search for strings in a text file matching a regular expression

Combine content with regular expression in file?

How to open a file and find a word?

Each variation that I tried led to:

1) freezing;

2) A listing of all words from a list containing 5-character permutations (I assume that he does, I did not go through and did not check all thousands of printed words); or

3) Print all 5-character permutations found in the words in the list (again, I guess he does).

Again, I am not looking for words containing 5-character permutations, I am looking for 5-character permutations that are complete words in their own right, so a line in a text file should be printed if this is a perfect match with the permutation.

? !

+5
4

, english.0 (, , ):

a = %w[b a h s v i e y k s a l d n]
dict = {}
a.permutation(5).each do |p|
  dict[p.join('')] = true
end

File.open('english.0').each_line do |line|
  line.chomp!.downcase!
  puts line if dict[line]
end

- ( , ), , " ", .

, . , .

+1

. , , ( 55 .!); , , ,

/^[bahsvieyksa]{5}$/

.

:

File.open('2of4brif.txt').each_line do |line|
  puts line if line.match(/^[bahsvieyksa]{5}$/)
end

+2

The easiest way is to simply count the occurrence of each char and compare:

a = %w[b a h s v i e y k s a l d n]
File.read('2of4brif.txt').split("\n").each do |line|
  puts line if line.size == 5 && line.chars.all?{|x| line.count(x) <= a.count(x)}
end
0
source

The following has been developed for me

File.open('file.txt').each_line do |line|
  puts line if line[/<regexp>/]
end
0
source

All Articles