Escaping dollars groovy - regex

I'm having trouble escaping double dollars from a string to be used with regex functions pattern/matcher.
This is part of the String:
WHERE oid_2 = $$test$$ || oid_2 = $$test2$$
and this is the closest code I've tried to get near the solution:
List<String> strList = new ArrayList<String>();
Pattern pattern = Pattern.compile("\$\$.*?\$\$");
log.debug("PATTERN: "+pattern)
Matcher matcher = pattern.matcher(queryText);
while (matcher.find()) {
strList.add(matcher.group());
}
log.debug(strList)
This is the debug output i get
- PATTERN: $$.*?$$
- []
So the pattern is actually right, but the placeholders are not found in the string.
As a test I've tried to replace "$$test$$" with "XXtestXX" and everything works perfectly. What am I missing? I've tried "/$" strings, "\\" but still have no solution.

Note that a $ in regex matches the end of the string. To use it as a literal $ symbol, you need to escape it with a literal backslash.
You used "\$\$.*?\$\$" that got translated into a literal string like $$.*?$$ that matches 2 end of string positions, any 0+ chars as few as possible and then again 2 end of strings, which has little sense. You actually would need a backslash to first escape the $ that is used in Groovy to inject variables into a double quoted string literal, and then use 2 backslashes to define a literal backslash - "\\\$\\\$.*?\\\$\\\$".
However, when you work with regex, slashy strings are quite helpful since all you need to escape a special char is a single backslash.
Here is a sample code extracting all matches from the string you have in Groovy:
def regex = /\$\$.*?\$\$/;
def s = 'WHERE oid_2 = $$test$$ || oid_2 = $$test2$$'
def m = s =~ regex
(0..<m.count).each { print m[it] + '\n' }
See the online demo.

Anyone who gets here might like to know another answer to this, if you want to use Groovy slashy strings:
myComparisonString ==~ /.*something costs [$]stuff.*/
I couldn't find another way of putting a $ in a slashy string, at least if the $ is to be followed by text. If, conversely, it is followed by a number (or presumably any non-letter), this will work:
myComparisonString ==~ /.*something costs \$100.*/
... the trouble being, of course, that the GString "compiler" (if that's its name) would recognise "$stuff" as an interpolated variable.

Related

Getting words Starting with symbol in dart

I'm trying to parse in Dart long strings containing hashtags, so far I tried various combinations with regexp but I cannot find the right use.
My code is
String mytestString = "#one #two, #three#FOur,#five";
RegExp regExp = new RegExp(r"/(^|\s)#\w+/g");
print(regExp.allMatches(mytestString).toString());
The desidered output would be a list of hahstags
#one #two #three #FOur #five
Thankyou in advance
You should not use a regex literal inside a string literal, or backslashes and flags will become part of the regex pattern. Also, omit the left-hand boundary pattern (that matches start of string or whitespace) if you need to match # followed with 1+ word chars in any context.
Use
String mytestString = "#one #two, #three#FOur,#five";
final regExp = new RegExp(r"#\w+");
Iterable<String> matches = regExp.allMatches(mytestString).map((m) => m[0]);
print(matches);
Output: (#one, #two, #three, #FOur, #five)
String mytestString = "#one #two, #three#FOur,#five";
RegExp regExp = new RegExp(r"/(#\w+)/g");
print(regExp.allMatches(mytestString).toString());
This should match all of the hashtags, placing them into capture groups for you to later use.

Surrounding one group with special characters in using substitute in vim

Given string:
some_function(inputId = "select_something"),
(...)
some_other_function(inputId = "some_other_label")
I would like to arrive at:
some_function(inputId = ns("select_something")),
(...)
some_other_function(inputId = ns("some_other_label"))
The key change here is the element ns( ... ) that surrounds the string available in the "" after the inputId
Regex
So far, I have came up with this regex:
:%substitute/\(inputId\s=\s\)\(\"[a-zA-Z]"\)/\1ns(/2/cgI
However, when deployed, it produces an error:
E488: Trailing characters
A simpler version of that regex works, the syntax:
:%substitute/\(inputId\s=\s\)/\1ns(/cgI
would correctly inser ns( after finding inputId = and create string
some_other_function(inputId = ns("some_other_label")
Challenge
I'm struggling to match the remaining part of the string, ex. "select_something") and return it as:
"select_something")).
You have many problems with your regex.
[a-zA-Z] will only match one letter. Presumably you want to match everything up to the next ", so you'll need a \+ and you'll also need to match underscores too. I would recommend \w\+. Unless more than [a-zA-Z_] might be in the string, in which case I would do .\{-}.
You have a /2 instead of \2. This is why you're getting E488.
I would do this:
:%s/\(inputId = \)\(".\{-}\)"/\1ns(\2)/cgI
Or use the start match atom: (that is, \zs)
:%s/inputId = \zs\".\{-}"/ns(&)/cgI
You can use a negated character class "[^"]*" to match a quoted string:
%s/\(inputId\s*=\s*\)\("[^"]*"\)/\1ns(\2)/g

Check if string contains single backslashes with regex

I have tried to fix this for a long time, and i just can't do it.
It could be any string, but this is an example:
"\This string \contains some\ backslashes\"
I need to make a regex that i can use to check that the string contains single backslashes.
I then need to convert the given string into (i can do the conversion):
"\\This string \\contains some\\ backslashes\\"
And then use regex to check that the string no long contains single backslashes.
Btw i dont have to use regex for this, i just need to be able to check the strings somehow.
It seems you just want to check if a string matches a regex pattern partially, namely, if it contains a literal backslash not preceded nor followed with a backslash.
Use
(?<!\\)\\(?!\\)
See the regex demo.
Sample Scala code:
val s = """"\This string\\ \contains some\ backslashes\""""
val rx = """(?<!\\)\\(?!\\)""".r.unanchored
val ismatch = s match {
case rx(_*) => true
case _ => false
}
println(ismatch)
See the Scala online demo.
Note:
"""(?<!\\)\\(?!\\)""".r.unanchored - this line declares a regex object and makes the pattern unanchored, so that no full string match is no longer required by the match block
Inside match, we use case rx(_*) as there is no capturing group defined inside the pattern itself
The pattern means: match a backslash (\\) that is not preceded with a backslash ((?<!\\)) and is not followed with a backslash ((?!\\)).
Not sure what you're asking.. are you asking how to write a String literal that represents the String you gave as an example? You could either escape the backslash with another backslash, or use triple quotes.
scala> "\\This string \\contains some\\ backslashes\\"
String = \This string \contains some\ backslashes\
scala> """\This string \contains some\ backslashes\"""
String = \This string \contains some\ backslashes\
And replace the backslashes using the same techniques.
scala> "\\This string \\contains some\\ backslashes\\".replace("\\","\\\\")
String = \\This string \\contains some\\ backslashes\\
or
scala> """\This string \contains some\ backslashes\""".replace("""\""","""\\""")
String = \\This string \\contains some\\ backslashes\\
But I have a feeling you want to do something else, like validate input. Maybe you could provide a bit more context?
Try This
val s = """\This string \contains some\ backslashes\"""
s.replaceAll("""\\""","""\\\\""")

Simple Regular Expression matching

Im new to regular expressions and Im trying to use RegExp on gwt Client side. I want to do a simple * matching. (say if user enters 006* , I want to match 006...). Im having trouble writing this. What I have is :
input = (006*)
input = input.replaceAll("\\*", "(" + "\\" + "\\" + "S\\*" + ")");
RegExp regExp = RegExp.compile(input).
It returns true with strings like BKLFD006* too. What am I doing wrong ?
Put a ^ at the start of the regex you're generating.
The ^ character means to match at the start of the source string only.
I think you are mixing two things here, namely replacement and matching.
Matching is used when you want to extract part of the input string that matches a specific pattern. In your case it seems that is what you want, and in order to get one or more digits that are followed by a star and not preceded by anything then you can use the following regex:
^[0-9]+(?=\*)
and here is a Java snippet:
String subjectString = "006*";
String ResultString = null;
Pattern regex = Pattern.compile("^[0-9]+(?=\\*)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group();
}
On the other hand, replacement is used when you want to replace a re-occurring pattern from the input string with something else.
For example, if you want to replace all digits followed by a star with the same digits surrounded by parentheses then you can do it like this:
String input = "006*";
String result = input.replaceAll("^([0-9]+)\\*", "($1)");
Notice the use of $1 to reference the digits that where captured using the capture group ([0-9]+) in the regex pattern.

Using Regex is there a way to match outside characters in a string and exclude the inside characters?

I know I can exclude outside characters in a string using look-ahead and look-behind, but I'm not sure about characters in the center.
What I want is to get a match of ABCDEF from the string ABC 123 DEF.
Is this possible with a Regex string? If not, can it be accomplished another way?
EDIT
For more clarification, in the example above I can use the regex string /ABC.*?DEF/ to sort of get what I want, but this includes everything matched by .*?. What I want is to match with something like ABC(match whatever, but then throw it out)DEF resulting in one single match of ABCDEF.
As another example, I can do the following (in sudo-code and regex):
string myStr = "ABC 123 DEF";
string tempMatch = RegexMatch(myStr, "(?<=ABC).*?(?=DEF)"); //Returns " 123 "
string FinalString = myStr.Replace(tempMatch, ""); //Returns "ABCDEF". This is what I want
Again, is there a way to do this with a single regex string?
Since the regex replace feature in most languages does not change the string it operates on (but produces a new one), you can do it as a one-liner in most languages. Firstly, you match everything, capturing the desired parts:
^.*(ABC).*(DEF).*$
(Make sure to use the single-line/"dotall" option if your input contains line breaks!)
And then you replace this with:
$1$2
That will give you ABCDEF in one assignment.
Still, as outlined in the comments and in Mark's answer, the engine does match the stuff in between ABC and DEF. It's only the replacement convenience function that throws it out. But that is supported in pretty much every language, I would say.
Important: this approach will of course only work if your input string contains the desired pattern only once (assuming ABC and DEF are actually variable).
Example implementation in PHP:
$output = preg_replace('/^.*(ABC).*(DEF).*$/s', '$1$2', $input);
Or JavaScript (which does not have single-line mode):
var output = input.replace(/^[\s\S]*(ABC)[\s\S]*(DEF)[\s\S]*$/, '$1$2');
Or C#:
string output = Regex.Replace(input, #"^.*(ABC).*(DEF).*$", "$1$2", RegexOptions.Singleline);
A regular expression can contain multiple capturing groups. Each group must consist of consecutive characters so it's not possible to have a single group that captures what you want, but the groups themselves do not have to be contiguous so you can combine multiple groups to get your desired result.
Regular expression
(ABC).*(DEF)
Captures
ABC
DEF
See it online: rubular
Example C# code
string myStr = "ABC 123 DEF";
Match m = Regex.Match(myStr, "(ABC).*(DEF)");
if (m.Success)
{
string result = m.Groups[1].Value + m.Groups[2].Value; // Gives "ABCDEF"
// ...
}