Syntax error in removing bad character in groovy - groovy

Hello I have a string like a= " $ 2 187.00" . I tried removing all the white spaces and the bad characters like a.replaceAll("\\s","").replace("$","") . but i am getting error
Impossible to parse JSON response: SyntaxError: JSON.parse: bad escaped character how to remove the bad character in this expression so that the value becomes 2187.00.Kindly help me .Thanks in advance

def a = ' $ 2 187.00'
a.replaceAll(/\s/,"").replaceAll(/\$/,"")
// or simply
a.replaceAll(/[\s\$]/,"")
It should return 2187.00.
Note
that $ has special meaning in double quoted strings literals "" , called as GString.
In groovy, you can user regex literal, using that is better than using regex with multiple escape sequences in string.

Related

python Using variable in re.search source.error("bad escape %s" % escape, len(escape)) [duplicate]

I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex?
For example, the user wants to search for Word (s): regex engine will take the (s) as a group. I want it to treat it like a string "(s)" . I can run replace on user input and replace the ( with \( and the ) with \) but the problem is I will need to do replace for every possible regex symbol.
Do you know some better way ?
Use the re.escape() function for this:
4.2.3 re Module Contents
escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.
def simplistic_plural(word, text):
word_or_plural = re.escape(word) + 's?'
return re.match(word_or_plural, text)
You can use re.escape():
re.escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
>>> import re
>>> re.escape('^a.*$')
'\\^a\\.\\*\\$'
If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.
If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).
Unfortunately, re.escape() is not suited for the replacement string:
>>> re.sub('a', re.escape('_'), 'aa')
'\\_\\_'
A solution is to put the replacement in a lambda:
>>> re.sub('a', lambda _: '_', 'aa')
'__'
because the return value of the lambda is treated by re.sub() as a literal string.
Usually escaping the string that you feed into a regex is such that the regex considers those characters literally. Remember usually you type strings into your compuer and the computer insert the specific characters. When you see in your editor \n it's not really a new line until the parser decides it is. It's two characters. Once you pass it through python's print will display it and thus parse it as a new a line but in the text you see in the editor it's likely just the char for backslash followed by n. If you do \r"\n" then python will always interpret it as the raw thing you typed in (as far as I understand). To complicate things further there is another syntax/grammar going on with regexes. The regex parser will interpret the strings it's receives differently than python's print would. I believe this is why we are recommended to pass raw strings like r"(\n+) -- so that the regex receives what you actually typed. However, the regex will receive a parenthesis and won't match it as a literal parenthesis unless you tell it to explicitly using the regex's own syntax rules. For that you need r"(\fun \( x : nat \) :)" here the first parens won't be matched since it's a capture group due to lack of backslashes but the second one will be matched as literal parens.
Thus we usually do re.escape(regex) to escape things we want to be interpreted literally i.e. things that would be usually ignored by the regex paraser e.g. parens, spaces etc. will be escaped. e.g. code I have in my app:
# escapes non-alphanumeric to help match arbitrary literal string, I think the reason this is here is to help differentiate the things escaped from the regex we are inserting in the next line and the literal things we wanted escaped.
__ppt = re.escape(_ppt) # used for e.g. parenthesis ( are not interpreted as was to group this but literally
e.g. see these strings:
_ppt
Out[4]: '(let H : forall x : bool, negb (negb x) = x := fun x : bool =>HEREinHERE)'
__ppt
Out[5]: '\\(let\\ H\\ :\\ forall\\ x\\ :\\ bool,\\ negb\\ \\(negb\\ x\\)\\ =\\ x\\ :=\\ fun\\ x\\ :\\ bool\\ =>HEREinHERE\\)'
print(rf'{_ppt=}')
_ppt='(let H : forall x : bool, negb (negb x) = x := fun x : bool =>HEREinHERE)'
print(rf'{__ppt=}')
__ppt='\\(let\\ H\\ :\\ forall\\ x\\ :\\ bool,\\ negb\\ \\(negb\\ x\\)\\ =\\ x\\ :=\\ fun\\ x\\ :\\ bool\\ =>HEREinHERE\\)'
the double backslashes I believe are there so that the regex receives a literal backslash.
btw, I am surprised it printed double backslashes instead of a single one. If anyone can comment on that it would be appreciated. I'm also curious how to match literal backslashes now in the regex. I assume it's 4 backslashes but I honestly expected only 2 would have been needed due to the raw string r construct.

what does this syntax error means. I wrote my code good. What is the problem?

why do I get this problem: SyntaxError: EOL while scanning string literal. Can someone please tell me where my fault is.
a = 2
b = 4
c = 8
print ("Forced Order:" 'a', '*' ('c' '+' 'b') '=’ a*(c+b))
The EOL error specifically appears because of '*' ('c' '+' 'b'). The computer believes that this code is trying to run a function, much like print(). The error pops up because a string cannot call a function like this.
What I imagine your trying to do is make the function output is Forced Order: a*(c+b)=24.That can be solved with two quick fixes:
First, there's a typo. '=’ should use ' not ’ on both sides.
Second, the parenthesis need to be parts of the string. The parenthesis in ('c' '+' 'b') are not part of any strings. Either they can be individually turned into strings like the rest of the function or, just like with the string "Forced Order:", the string "a*(c+b)" can be written out as one string instead of concatenating a series of single characters.

regex with named capture fails in XRegExp but works fine on regex101.com [duplicate]

In the regex below, \s denotes a space character. I imagine the regex parser, is going through the string and sees \ and knows that the next character is special.
But this is not the case as double escapes are required.
Why is this?
var res = new RegExp('(\\s|^)' + foo).test(moo);
Is there a concrete example of how a single escape could be mis-interpreted as something else?
You are constructing the regular expression by passing a string to the RegExp constructor.
\ is an escape character in string literals.
The \ is consumed by the string literal parsing…
const foo = "foo";
const string = '(\s|^)' + foo;
console.log(string);
… so the data you pass to the RegEx compiler is a plain s and not \s.
You need to escape the \ to express the \ as data instead of being an escape character itself.
Inside the code where you're creating a string, the backslash is a javascript escape character first, which means the escape sequences like \t, \n, \", etc. will be translated into their javascript counterpart (tab, newline, quote, etc.), and that will be made a part of the string. Double-backslash represents a single backslash in the actual string itself, so if you want a backslash in the string, you escape that first.
So when you generate a string by saying var someString = '(\\s|^)', what you're really doing is creating an actual string with the value (\s|^).
The Regex needs a string representation of \s, which in JavaScript can be produced using the literal "\\s".
Here's a live example to illustrate why "\s" is not enough:
alert("One backslash: \s\nDouble backslashes: \\s");
Note how an extra \ before \s changes the output.
As has been said, inside a string literal, a backslash indicates an escape sequence, rather than a literal backslash character, but the RegExp constructor often needs literal backslash characters in the string passed to it, so the code should have \\s to represent a literal backslash, in most cases.
A problem is that double-escaping metacharacters is tedious. There is one way to pass a string to new RegExp without having to double escape them: use the String.raw template tag, an ES6 feature, which allows you to write a string that will be parsed by the interpreter verbatim, without any parsing of escape sequences. For example:
console.log('\\'.length); // length 1: an escaped backslash
console.log(`\\`.length); // length 1: an escaped backslash
console.log(String.raw`\\`.length); // length 2: no escaping in String.raw!
So, if you wish to keep your code readable, and you have many backslashes, you may use String.raw to type only one backslash, when the pattern requires a backslash:
const sentence = 'foo bar baz';
const regex = new RegExp(String.raw`\bfoo\sbar\sbaz\b`);
console.log(regex.test(sentence));
But there's a better option. Generally, there's not much good reason to use new RegExp unless you need to dynamically create a regular expression from existing variables. Otherwise, you should use regex literals instead, which do not require double-escaping of metacharacters, and do not require writing out String.raw to keep the pattern readable:
const sentence = 'foo bar baz';
const regex = /\bfoo\sbar\sbaz\b/;
console.log(regex.test(sentence));
Best to only use new RegExp when the pattern must be created on-the-fly, like in the following snippet:
const sentence = 'foo bar baz';
const wordToFind = 'foo'; // from user input
const regex = new RegExp(String.raw`\b${wordToFind}\b`);
console.log(regex.test(sentence));
\ is used in Strings to escape special characters. If you want a backslash in your string (e.g. for the \ in \s) you have to escape it via a backslash. So \ becomes \\ .
EDIT: Even had to do it here, because \\ in my answer turned to \.

Why does "\1" inside a triple-quoted string evaluate to a unicode 0x1 code point

I wanted a String containing a text \1.
What I did was (the real string was longer but it's not important):
'''
\1
'''
Which resulted in a String containing a unicode 0x1 codepoint.
I think what I should've done is just escape the backslash like this:
'''
\\1
'''
What I don't understand is why Groovy didn't report an error here. I thought unicode escapes are supposed to look like \u1?
Instead of a syntax error I got a runtime exception when I tried to put this String into an XML element:
An invalid XML character (Unicode: 0x1) was found in the element content of the document.
The \ (backward slash) symbol is an escape symbol. If you mean to use it literally, you must escape it itself: \\.
When you escape any character, the character is interpreted to have special meaning. In the case of the \1 sequence, it just happens that this can be interpreted as the 0x01 codepoint.
This is the same in Java Strings.
If you want to not have to escape characters in Groovy, use slashy strings:
def x = /\1/
assert x == "\\1"
which also works as multiline:
def x = /
\1
/

define a character string containing "

I wish to define a character variable as: a"", as in: my.string <- 'a""' Nothing I have tried works. I always get: "a\"\"", or some variation thereof.
I have been reading the documentation for: grep, strsplit, regex, substr, gregexpr and other functions for clues on how to tell R that " is a character I want to keep unchanged, and I have tried maybe a hundred variations of a"" by adding \\, \, /, //, [], _, $, [, #.
The only potential example I can find on the internet of a string including " is: ‘{}>=40*" years"’ from here: http://cran.r-project.org/doc/manuals/R-lang.html However, that example is for performing a mathematical operation.
Sorry for such a very basic question. Thank you for any advice.
The backslashes is an artifact of the print method. In fact the default print surrounds your string with quotes. You can disable this by setting argument quote to FALSE.
For example You can use :
print(my.string,quote=FALSE)
[1] a""
But I would use cat or write like this :
cat(my.string)
a""
write(my.string,"")
a""
Using substr, one sees that the backslashes seem just to be an artefact of printing:
substr(my.string,2,2)
gives
[1] "\""
also, the string length is as you want it:
> nchar(my.string)
[1] 3
if you want to print your string without the backslashes, use noquote :
> noquote(my.string)
[1] a""

Resources