I use the following in GWT to find the backslash from a string and replace with \\.
String name = "\path\item";
name = RegExp.compile("/\\/g").replace(name, "\\\\");
But it does not work, because for name=\path\item returns name=\path\item.
ok i follow the recomendation of Thomas Broyer and the first RegExp.compile("\\", "g").replace(bgPath, "\\\\") gives:
Caused by: com.google.gwt.core.client.JavaScriptException: (SyntaxError): trailing \ in regular expression
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:237)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:132)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.regexp.shared.RegExp$.compile(RegExp.java)
at com.ait.gwt.authtool.client.ui.TicketViewer.<init>(TicketViewer.java:197)
at com.ait.gwt.authtool.client.AuthTool.onViewTicketBtnClicked(AuthTool.java:1942)
at com.ait.gwt.authtool.client.AuthTool.onMessageReceived(AuthTool.java:1995)
at com.ait.gwt.authtool.client.events.MessageReceivedEvent.dispatch(MessageReceivedEvent.java:44)
at com.ait.gwt.authtool.client.events.MessageReceivedEvent.dispatch(MessageReceivedEvent.java:1)
at com.google.gwt.event.shared.GwtEvent.dispatch(GwtEvent.java:1)
at com.google.web.bindery.event.shared.SimpleEventBus.doFire(SimpleEventBus.java:193)
at com.google.web.bindery.event.shared.SimpleEventBus.fireEvent(SimpleEventBus.java:88)
at com.google.gwt.event.shared.SimpleEventBus.fireEvent(SimpleEventBus.java:52)
and the second bgPath.replaceAll("\\", "\\\\") gives:
Caused by: java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at com.ait.gwt.authtool.client.ui.TicketViewer.<init>(TicketViewer.java:198)
but when i type: bgPath = bgPath.replaceAll(Pattern.quote("\"), Matcher.quoteReplacement("\\"));
works normally(!!) as it gives: [INFO] [gwt_app] - !!! bgPath=Background\\Cartoon\\image
RegExp.compile is the equivalent to new Regexp in JS, so the argument is not a regexp literal. Your code should read RegExp.compile("\\", "g").
But for this particular case, name.replace("\\", "\\\\") should be enough.
Related
I am using below regular expression string to replace the supplied string with ****
String output=output.replaceAll("(?<!\\w)(?i)"+requesterView.getFirstname()+"(?!\\w)","****");
Above the supplied string +91
If it contains + then getting below exception
java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 12
(?<!\w)(?i)(+91)(?!\w)
^
at java.util.regex.Pattern.error(Pattern.java:1955)
at java.util.regex.Pattern.sequence(Pattern.java:2123)
at java.util.regex.Pattern.expr(Pattern.java:1996)
at java.util.regex.Pattern.group0(Pattern.java:2905)
at java.util.regex.Pattern.sequence(Pattern.java:2051)
at java.util.regex.Pattern.expr(Pattern.java:1996)
at java.util.regex.Pattern.compile(Pattern.java:1696)
at java.util.regex.Pattern.<init>(Pattern.java:1351)
at java.util.regex.Pattern.compile(Pattern.java:1028)
How to resolve above exception ?
You need to escape regex meta-characters in your input String, which you can do with the Pattern.quote(String str) static method :
String output=output.replaceAll("(?<!\\w)(?i)"+Pattern.quote(requesterView.getFirstname())+"(?!\\w)","****");
Currently Java tries to parse the tokens of the input string (+91) as regex tokens and fails to make sense of the + meta-character in the context it's found in. Additionnally the parenthesis would have been understood as a capturing group.
Like Aaron mentioned you need to quote the regular expression.
This can be achieved either with Pattern.quote or using \Q together with \E. Here is an example:
public static String transformRegex(String input, String testStr) {
return input.replaceAll("(?<!\\w)(?i)\\Q" + testStr + "\\E(?!\\w)", "****");
}
Here is a test of the method above:
String output = transformRegex("+91 123123123", "+91");
System.out.println(output);
This prints:
**** 123123123
I'm trying to extract from a string variables with the following format: ${var}
Given this string:
val s = "This is a string with ${var1} and ${var2} and {var3}"
The result should be
List("var1","var2")
This is the attempt, it ends in an exception. What's wrong with this regex?
val pattern = """\${([^\s}]+)(?=})""".r
val s = "This is a string with ${var1} and ${var2} and {var3}"
val vals = pattern.findAllIn(s)
println(vals.toList)
and the exception:
Exception in thread "main" java.util.regex.PatternSyntaxException:
Illegal repetition near index 1 \${([^\s}]+)(?=})
NOTE :- { in regex have special meaning. It denotes range. e.g. a{2,10} denotes match a in between 2 to 10 times. So you need to escape {.
Solution 1
val pattern = """\$\{([^\s}]+)(?=})""".r
You need to access the first capturing group for finding the result and then change it to list.
Solution 2
You can also use lookbehind like
val pattern = """(?<=\$\{)[^\s}]+(?=})""".r
Ideone Demo
Groovy 2.4 here. I am trying to build a regex that will filter out all the following characters:
`,./;[]-&<>?:"()|
Here's my best attempt:
static void main(String[] args) {
// `,./;[]-&<>?:"()|
String regex = "`,./;[]-&<>?:\"()|"
String test = "ooekrofkrofor ` oxkeoe , wdkeodeko / kodek ] woekoedk \" swjiej ' wsjwdjeiji :"
println test.replaceAll(regex, "")
}
However this produces a compile error on the regex string definition, complaining:
illegal character range (to < from)
Not sure if this is a Java or Groovy thing, but I can't figure out how to define the regex properly so that it quiets the error and correctly strips these "illegal characters" out of my string. Any ideas?
It seems to me you want to remove all the characters listed in your regex variable. The problem is that you declared a sequence while you need a character class (enclose the characters with []).
See Groovy demo:
String regex = "[`,./;\\[\\]&<>?:\"()|-]+"
^ ^^^^^^ ^ ^
String test = "ooekrofkrofor ` oxkeoe , wdkeodeko / kodek ] woekoedk \" swjiej ' wsjwdjeiji :"
println test.replaceAll(regex, "")
Output: ooekrofkrofor oxkeoe wdkeodeko kodek woekoedk swjiej ' wsjwdjeiji
The pattern now contains a character class matching any of the characters defined inside it - [`,./;\[\]&<>?:\"()|-] - one or more times due to the + quantifier. Note that inside the character class, ] and [ must always be escaped, and the - can be left unescaped when placed at the start/end of the character class.
You need to escape a few special characters in your pattern:
String regex = "[`,./;\\[]\\-&<>?:\"\\(\\)|]+"
Note using double \\ to turn them into a single \ in the string, so when the pattern is parsed, the next character is escaped.
I want to find the number between [/ and ] (12345 in this case).
I have written such code:
float num;
string line = "A111[/12345]";
boost::regex e ("[/([0-9]{5})]");
boost::smatch match;
if (boost::regex_search(line, match, e))
{
std::string s1(match[1].first, match[1].second);
num = boost::lexical_cast<float>(s1); //convert to float
cout << num << endl;
}
However, I get this error: The error occurred while parsing the regular expression fragment: '/([0-9]{5}>>>HERE>>>)]'.
You need to double escape the [ and ] that special characters in regex denoting character classes. The correct regex declaration will be
boost::regex e ("\\[/([0-9]{5})\\]");
This is necessary because C++ compiler also uses a backslash to escape entities like \n, and regex engine uses the backslash to escape special characters so that they are treated like literals. Thus, backslash gets doubled. When you need to match a literal backslash, you will have to use 4 of them (i.e. \\\\).
Use the following (escape [ and ] because they are special characters in regex meaning a character class):
\\[/([0-9]{5})\\]
^^ ^^
I am trying to use std::regex_replace in C++11 (Visual Studio 2013) but the regex i am trying to create is throwing an exception:
Microsoft C++ exception: std::regex_error at memory location 0x0030ED34
Why is this the case? This is my definition:
std::string regexStr = R"(\([A - Za - z] | [0 - 9])[0 - 9]{2})";
std::regex rg(regexStr); <-- This is where the exception thrown
line = std::regex_replace(line, rg, this->protyp->getUTF8Character("$&"));
What i want to do: Find all matches inside a string which are of the following format:
"\X99" OR "\999"
where X = A-Z or a-z and 9 = 0-9.
I also tried to use the boost regex library, but it also throws an exeception.
(Another question: Can i use the backreference as i am doing in the last line? I want to replace dynamically according to the match)
Thanks for any help
As per the above comments, you need to fix your regex: to match a literal backslash you need to use "\\\\" (or R("\\")).
My code that shows all the first captured groups:
string line = "\\X99 \\999";
string regexStr = "(\\\\([A-Za-z]|[0-9])[0-9]{2})";
regex rg(regexStr); //<-- This is where the exception was thrown before
smatch sm;
while (regex_search(line, sm, rg)) {
std::cout << sm[1] << std::endl;
line = sm.suffix().str();
}
Output:
\X99
\999
Regarding using a method call inside a replacement string, I do not find such a functionality in the regex_replace documentation:
fmt - the regex replacement format string, exact syntax depends on the
value of flags