Coffeescript supports strings interpolation:
user = "world"
greeting = "Hello #{user}!"
Is it possible to use interpolation in regex just like in strings? E.g.
regex = /Hello #{user}/g
P.S. I know that I can use RegExp(greeting, 'g'), I just want a bit cleaner code.
Block Regular Expressions (Heregexes) support interpolation.
Block Regular Expressions
Similar to block strings and comments,
CoffeeScript supports block regexes — extended regular expressions
that ignore internal whitespace and can contain comments and
interpolation. Modeled after Perl's /x modifier, CoffeeScript's block
regexes are delimited by /// and go a long way towards making complex
regular expressions readable.
This coffeescript code:
name="hello"
test=///#{name}///
compiles to
var name, test;
name = "hello";
test = RegExp("" + name);
Related
I have the following json code in my powershell script.
I set the $variable to 1111111111
$jsonfile = '{"Version": "2012-10-17","Statement": {"Effect": "Allow","Action": "sts:AssumeRole","Resource": "arn:aws:iam::$variable:role/xxxxxx"}}'
The output gives ....arn:aws:iam::$variable:role/xxxxxx..... instead of ....arn:aws:iam::1111111111:role/xxxxxx
The problem is that I must use the single quote for the json string otherwise I will get an error. If I use single quote I wont be able to put the variables inside the string. How do I workaround this problem?
There are various ways to solve your problem, but perhaps the easiest approach is to use PowerShell's string interpolation:
use a double-quoted string overall to enable interpolation of embedded variable references and subexpressions ($(...)).
escape embedded " chars. as `" (using backticks)
disambiguate variable references by enclosing the variable name in {...}.
Simplified example:
PS> $variable='111'
PS> "{`"Version`": `"arn:aws:iam::${variable}:role/xxxxxx`"}}"
{"Version": "arn:aws:iam::111:role/xxxxxx"}}
Note that enclosing variable names in {...} in interpolated strings is only necessary if the following char. could be misinterpreted as part of the variable name.
A : following the variable name - as is the case here - is such a case, because PS variables can have a scope specifier preceding the variable name that is separated from the variable name with :, such as in $env:USERNAME.
DAXaholic's helpful answer shows an alternative based on PowerShell's binary -f operator, which is essentially the same as the .NET framework's String.Format method; as such:
it introduces additional complexity, such as needing to know what its escaping rules are ({ chars. must be escape as {{, and how to format its arguments specified on the RHS of -r ({0} refers to the 1st RHS argument, ...)
on the flip side, -f offers many sophisticated formatting options.
Also, consider use of the Convert*-Json cmdlets his answer demonstrates: even though they're less performant, they ultimately make manipulation of JSON much easier and more robust.
Alternatives in the realm of native PowerShell code:
String concatenation with the binary + operator:
'{"Version": "arn:aws:iam::' + $variable + ':role/xxxxxx"}}'
String templating with $ExecutionContext.InvokeCommand.ExpandString():
$variable='111'
$tmpl = '{"Version": "arn:aws:iam::${variable}:role/xxxxxx"}}' # string template *literal*
$ExecutionContext.InvokeCommand.ExpandString($tmpl) # performs on-demand interpolation
Another solution would be
$jsonfile = '{{"Version": "2012-10-17","Statement": {{"Effect": "Allow","Action": "sts:AssumeRole","Resource": "arn:aws:iam::{0}:role/xxxxxx"}}}}' -f $variable
So you have to escape the braces with another brace but in your case you have fewer braces than quotes so it is "less obfuscation" :)
In your case, maybe the simplest solution is just concatenating the strings together instead of using string formatting / interpolation.
In addition you could also go the way with the JSON cmdlets:
$jsonfile |
ConvertFrom-Json |
% { $_.Statement.Resource = "arn:aws:iam::${variable}:role/xxxxxx"; $_ } |
ConvertTo-Json
I have a preprocessor macro that represents a hierarchical path into my design.
Example:
`define HPATH top.chip.block
I need to construct a string which holds the value of `HPATH, so in my example the string should equal top.chip.block.
Is there a way to construct such a string?
None of the following attempts worked:
string hpath;
hpath = "`HPATH"; // Results in hpath = "`HPATH"
hpath = \"``HPATH\"; // Doesn't compile
hpath = `HPATH; // Doesn't compile
I want hpath to be equivalent to doing this assignment hpath = "top.chip.block", but by using `HPATH instead of specifying the path again.
I cannot use %m because I need the string within my top-level UVM environment, not within a module.
A little more background: the reason I want to do this is because I am using backdoor register access in the UVM class library. The backdoor API requires setting the hdl_path to the blocks within the design, as a string. I already have `defines for the hierarchical paths and am trying to reuse those when specifying the hdl_paths so I don't have the same path defined twice. My testbench will use both the hierarchical path and the string path.
It's not possible to use a `define macro within a string literal. According to the SystemVerilog LRM:
Macro substitution and argument substitution shall not occur within string literals.
However a string literal can be constructed by using a macro that takes an argument and including the quotes in the macro by using ``"`.
Again, from the LRM:
An `" overrides the usual lexical meaning of " and indicates that the expansion shall include the quotation
mark, substitution of actual arguments, and expansions of embedded macros. This allows string literals to be
constructed from macro arguments.
So this works:
`define STRINGIFY(x) `"x`"
`define HPATH top.chip.block
string hpath = `STRINGIFY(`HPATH);
$display(hpath); // Output: "top.chip.block"
The example code can be run here: http://www.edaplayground.com/s/4/879
I know this is an old thread, but I thought I'd share our solution. The use of the $sformatf allows additional information to be added if needed.
`define STRINGIFY(DEFINE) $sformatf("%0s", `"DEFINE`")
I think this is what you're looking for.
`define HPATH `"top.chip.block`"
string hpath = `HPATH;
As toolic pointed out, the escape sequence %m will give you the current hierarchy when used in a $display statement so that may be a better option.
In Sas9, how can I replace all the , \ / or spaces, and other special characters of my choosing with underscores? A solution either in a datastep or in macro functions would do the trick, I'm just looking for a method to do it.
Thanks
You can use the Perl regular expression functionality built into SAS.
data tmp;
set tmp;
var1 = prxchange('s/[,\/\\]/_/', -1, var);
run;
or something similar.
The translate function might be what you're looking for
field2 = translate(trim(field_name),'_______',' ,.\/()')
Make sure to have as many underscores as you have special characters. Also, because you're translating spaces, you have to use the trim function or else you'll get a bunch of underscores after the name.
In scala, "here docs" is begin and end in 3 "
val str = """Hi,everyone"""
But what if the string contains the """? How to output Hi,"""everyone?
Since unicode escaping via \u0022 in multi-line string literals won’t help you, because they would be evaluated as the very same three quotes, your only chance is to concatenate like so:
"""Hi, """+"""""""""+"""everyone"""
The good thing is, that the scala compiler is smart enough to fix this and thus it will make one single string out of it when compiling.
At least, that’s what scala -print says.
object o {
val s = """Hi, """+"""""""""+"""everyone"""
val t = "Hi, \"\"\"everyone"
}
and using scala -print →
Main$$anon$1$o.this.s = "Hi, """everyone";
Main$$anon$1$o.this.t = "Hi, """everyone";
Note however, that you can’t input it that way. The format which scala -print outputs seems to be for internal usage only.
Still, there might be some easier, more straightforward way of doing this.
It's a totally hack that I posted on a similar question, but it works here too: use Scala's XML structures as an intermediate format.
val str = <a>Hi,"""everyone</a> text
This will give you a string with three double quotation marks.
you can't
scala heredocs are raw strings and don't use any escape codes
if you need tripple quotes in a string use string-concatenation add them
You can't using the triple quotes, as far as I know. In the spec, section 1.3.5, states:
A multi-line string literal is a sequence of characters enclosed in triple quotes
""" ... """. The sequence of characters is arbitrary, except that it may contain
three or more consuctive quote characters only at the very end. Characters must
not necessarily be printable; newlines or other control characters are also permitted.
Unicode escapes work as everywhere else, but none of the escape sequences in
(§1.3.6) is interpreted.
So if you want to output three quotes in a string, you can still use the single quote string with escaping:
scala> val s = "Hi, \"\"\"everyone"
s: java.lang.String = Hi, """everyone
How to match strings in shell-style in Perl? For instance:
foo*
{bar,baz}.smth
joe?
foobar[0-9]
Using regular expressions
Your examples would be:
/foo.*(bar|baz)\.smth joe/
/foobar\d/
However, if what you actually wanted was shell-like filename expansion (e.g. the above was in context of ls foobar[0-9] ), use glob() function:
my #files = glob("foo* {bar,baz}.smth joe");
my #foobar_files = glob("foobar[0-9]");
Please note that the syntax of regular expressions in Perl is NOT that of filename expansion language
File::FnMatch exposes your system's fnmatch(3) implementation, which is probably what implements the shell's wildcard patterns for you.
(Note that {bar,baz}.smth is not matching per se, it is simply "brace expansion" of strings.)