Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to Regex

Tags:

elixir

I have this code

reg=~r/(\d{4}.csv)/
raw="some craxy trashy text blabla 0044.csv"
Regex.scan(reg,raw, capture: :all_but_first)

This returns 0044.csv.

However, I need to load the ~r/(\d{4}.csv)/ from a database, so I will save it as

"~r/(\d{4}.csv)/"

This is a string. When I load it to a variable, it will be a string.

How can I pass it to a Regex.scan?

like image 634
ramstein Avatar asked Feb 03 '16 16:02

ramstein


People also ask

How do you convert a string to a regular expression in Python?

All you need to do is create a string with the value of input between ( and ) . If the string has any of the special regex expressions, it will not match what is in the file. For example 'abc\d' would match abc1 abc2 and so forth.

What is the regex for a string?

Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .

How do you create a string in regex?

Example : ^\d{3} will match with patterns like "901" in "901-333-". It tells the computer that the match must occur at the end of the string or before \n at the end of the line or string. Example : -\d{3}$ will match with patterns like "-333" in "-901-333". A character class matches any one of a set of characters.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


1 Answers

You can use Regex.compile/2 or Regex.compile!/2

iex> Regex.compile("(\\d{4}.csv)")    
{:ok, ~r/(\d{4}.csv)/}

You will need an extra backslash for escaping, otherwise you will end up with:

iex> Regex.compile("(\d{4}.csv)")    
{:ok, ~r/(\x7F{4}.csv)/}
like image 106
Gazler Avatar answered Oct 19 '22 01:10

Gazler