Regular expression compilation?

I would like to create regular expressions that reuse the regular expression in the new regular expression.

Is this possible in Ruby?

For example, to simplify this parsing, similar to assembly:

LABELED_INSTR = /(\w+):(movi|addi)\s+(\w+),(\w+),(w+)/ NON_LABELED_INSTR = /(movi|addi)\s+(\w+),(\w+),(w+)/ 

I would like to resort to:

 IMMEDIATE = /(movi|addi)/ 

But then I do not know how to share this regular expression in the previous two.

Any clues?

+6
source share
2 answers

Of course, regular expressions can be reused (or composed) inside other regular expressions. Here's an example that combines two regular expressions to make a third:

 >> a = /boo/ => boo >> b = /foo/ => foo >> c = /#{a}|#{b}/ => -mix:boo-mix:foo >> if "boo" =~ c >> puts "match!" >> end match! => nil 

Your example is very similar. Here it will be:

 IMMEDIATE = /(movi|addi)/ LABELED_INSTR = /(\w+):#{IMMEDIATE}\s+(\w+),(\w+),(w+)/ NON_LABELED_INSTR = /#{IMMEDIATE}\s+(\w+),(\w+),(w+)/ 
+17
source

You can also use the lines:

 IMMEDIATE = "(movi)|(addi)" LABELED_INSTR = Regexp.new("(\\w+):#{IMMEDIATE}\\s+(\\w+),(\\w+),(w+)/") NON_LABELED_INSTR = Regexp.new(IMMEDIATE + "\\s+(\\w+),(\\w+),(w+)/") 

Note that you should avoid inverted slashes.

0
source

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


All Articles