I have a string value which received from input field.
String searchingText = getText();
After i receive a string i search this string. But if string contains \ symbol my search is failed.
I know about special characters and try to replace :
searchingText = searchingText.replaceAll("\\","\\\\");
But it give me error and app was shutdown.
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
After research i founded a regex and try to replace with matcher :
Map<String,String> sub = new HashMap<String,String>();
sub.put("\n", "\\\\n");
sub.put("\r", "\\\\r");
sub.put("\t", "\\\\t");
StringBuffer result = new StringBuffer();
Pattern regex = Pattern.compile("\\n|\\r|\\t");
Matcher matcher = regex.matcher(bodySearchText);
In the end i will want to get a string - searchingText = \\ instead of searchingText = \
Please any solutions.
You should do:
string = string.replaceAll("\\\\", "\\\\\\\\");
Note that in Java, \ is written as \\. So replaceAll will see \\ as \, which is not what you want.
Instead, you can use replace that accepts String and not a regex.
change this
searchingText = searchingText.replaceAll("\\","\\\\");
to
searchingText = searchingText.replaceAll("\\\\","\\\\\\");
the replaceAll() will take \\ as \ .
for more details read here
Related
I want to check a string to see if it contains $wildcard$, and ONLY if it does I want to extract the value between the "$ $", which I'll use to retrieve a replacement. Then replace the full new string (removing the $ $ as well)
Edit: managed to get this working demo
String subject = "test/$name$/something";
String replace = "foo_bar";
Pattern regex = Pattern.compile("(\\$).*?(\\$)");
Matcher m = regex.matcher(subject);
StringBuffer b= new StringBuffer();
while (m.find()) {
String something = m.group(0);
System.out.println(something);
m.appendReplacement(b, replace);
}
m.appendTail(b);
String replaced = b.toString();
System.out.println(replaced);
Gives me the output of
$name$
test/foo_bar/something
I could substring to remove the lead/trailing $ but is there a way to split these into groups so I can just get what is between $ $. But also ensuring that the initial check ensures it has a start and end $
Add another matching group for the content of the tag:
Pattern.compile("(\\$)(.*?)(\\$)");
Remove unnecessary capturing groups from both \\$, set the capturing group on the pattern that matches what is between two $ chars (and the most efficient construct to use here is a negated character class [^$]), and then just grab the value of .group(1):
String subject = "test/$name$/something";
String replace = "foo_bar";
Pattern regex = Pattern.compile("\\$([^$]*)\\$"); // ONLY 1 GROUP ROUND [^$]*
Matcher m = regex.matcher(subject);
StringBuffer b= new StringBuffer();
while (m.find()) {
String something = m.group(1); // ACCESS GROUP 1
System.out.println(something);
m.appendReplacement(b, replace);
}
m.appendTail(b);
String replaced = b.toString();
System.out.println(replaced);
See the Java demo
Result:
name
test/foo_bar/something
Pattern details
\\$ - a $ char
([^$]*) - Capturing group 1 matching zero or more chars other than $ char
\\$ - a $ char.
It has slightly different syntax that you're asking for, but check out Apache Commons Text: https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StrSubstitutor.html
This will let you do things like:
Map<String,String> substitutions = ImmutableMap.of("name", "foo_bar");
String template = "/test/${name}/something";
StrSubstitutor substitutor = new StrSubstitutor(substitutions);
System.out.println(substitutor.replace(template));
You could build your own Map to populate with your substitution values.
I am using java replaceAll() method to replace part of String with another String and its working great but, the problem comes when my file name contains characters like $ ^ + ( ) { } [ ] etc. In this case pattern matching fails and the original String remains as it is.
Sample code to show case my use case is as follow:
String messageBody = "src=\"http://thinconnect.interactcrm.com:36061/FileDownloader/4/outbound/31358/file+name.jpeg\" style=\"height:225px\"";
messageBody = messageBody.replaceAll("(http|https)://(?:[^\\s]*)/FileDownloader/4/outbound/31358/file+name.jpeg", "cid: 14890411127853");
System.out.println(messageBody);
The expected output is:
src="cid: 14890411127853" style="height:225px"
but it gives:
src="http://thinconnect.interactcrm.com:36061/FileDownloader/4/outbound/31358/file+name.jpeg" style="height:225px"
How can I get it working by ignoring special characters that we use to form regex expression from my file name.
Thanks in advance!
You have unescaped metacharacters in your URL pattern, including a plus and a literal dot. Escape them, using the following pattern:
(http|https)://(?:[^\\s]*)/FileDownloader/4/outbound/31358/file\\+name\\.jpeg
^^^ escape dot and plus sign
Full code:
String messageBody = "src=\"http://thinconnect.interactcrm.com:36061/FileDownloader/4/outbound/31358/file+name.jpeg\" style=\"height:225px\"";
messageBody = messageBody.replaceAll("(http|https)://(?:[^\\s]*)/FileDownloader/4/outbound/31358/file\\+name\\.jpeg", "cid: 14890411127853");
System.out.println(messageBody);
Output:
src="cid: 14890411127853" style="height:225px"
Update:
If you don't know in advance what the exact pattern will be, but you know it might have metacharacters, which would require escaping for use in a replacement, then Java provides a method for this: Pattern.quote()
To see how it works, we can split your pattern into two parts:
String part1 = "(http|https)://(?:[^\\s]*)";
String part2 = Pattern.quote("/FileDownloader/4/outbound/31358/file+name.jpeg");
messageBody = messageBody.replaceAll(part1 + part2, "cid: 14890411127853");
From the documentation for Pattern.quote():
This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.
Metacharacters or escape sequences in the input sequence will be given no special meaning.
You just have to escape those characters using a backslash (\)
example:
String messageBody = "src=\"http://thinconnect.interactcrm.com:36061/FileDownloader/4/outbound/31358/file+name.jpeg\" style=\"height:225px\"";
messageBody = messageBody.replaceAll("(http|https)://(?:[^\\s]*)/FileDownloader/4/outbound/31358/file\\+name\\.jpeg", "cid: 14890411127853");
similarly
String messageBody = "src=\"http://thinconnect.interactcrm.com:36061/FileDownloader/4/outbound/31358/file$name.jpeg\" style=\"height:225px\"";
messageBody = messageBody.replaceAll("(http|https)://(?:[^\\s]*)/FileDownloader/4/outbound/31358/file\\$name\\.jpeg", "cid: 14890411127853");
Did it this way.
final String[] metaCharacters = {"^","$","{","}","[","]","(",")",".","+","-","&"};
String filePath = "/4/outbound/31358/file+name.jpeg";
for(String c: metaCharacters){
if(filePath.contains(c)){
filePath = filePath.replace(c, "\\"+c);
}
}
String messageBody = "src=\"http://thinconnect.interactcrm.com:36061/FileDownloader/4/outbound/31358/file+name.jpeg\" style=\"height:225px\"";
System.out.println(messageBody);
messageBody = messageBody.replaceAll("(http|https)://(?:[^\\s]*)/FileDownloader"+filePath, "cid: 14890411127853");
System.out.println(messageBody);
I am working with regex for fetching string value containing quotes. In below example I want to get value summary key as "Here is "summary". Currently I am getting only "Here is " as output of below program. I want to escape all double quotes those comes in-between first and final double quote.
String in = "summary = \"Here is \"summary\"";
Pattern p = Pattern.compile("'(.*?)'|\"(.*?)[^\\\"]+\"");
Matcher m = p.matcher(in);
while(m.find()) {
System.out.println(m.group());
}
Thanks for any help.
use this one:
/\\["']((?:[^"\\]|\\.)*)\\["']/
Demo : https://regex101.com/r/033EKx/1
Remember: When trying to build regex by " , \ should change to \\ and other special characters (" and ')
rStr = "/\\\\[\"\']((?:[^\"\\\\]|\\\\.)*)\\\\[\"\']/" ;
I am using java replaceAll() method to escape new line characters
String comment = "ddnfa \n \r \tdnfadsf ' \r t ";
comment = comment.replaceAll("(\\n|\\r|\\t)","\\\\$1");
System.out.println(comment);
But the above code is still inserting new line.
Is there a way to output the comment exactly the same (i.e. with \n and \r instead of inserting new line)?
UPDATE:
I ended up using:
comment = comment.replaceAll("\\n","\\\\n")
.replaceAll("\\r","\\\\r")
.replaceAll("\\t","\\\\t");
You'll have to go one-by-one, since the new-line character U+000A has nothing to do with the two-character escape sequence \n:
comment = comment.replaceAll("\n","\\\\n");
comment = comment.replaceAll("\r","\\\\r");
comment = comment.replaceAll("\t","\\\\t");
you will have to do it character by character:
comment = comment.replaceAll("\n","\\\\n");
comment = comment.replaceAll("\r","\\\\r");
comment = comment.replaceAll("\t","\\\\t");
another solution is to escape the String as a Java String using this function:
comment = org.apache.commons.lang.StringEscapeUtils.escapeJava(comment);
This will make the String look exactly like the String in the Java Code, but it will also show other escape sequences (like \\, \" etc).
But maybe thats exactly what you want
Hard way: using Matcher
String comment = "ddnfa \n \r \tdnfadsf ' \r t ";
Map<String,String> sub = new HashMap<String,String>();
sub.put("\n", "\\\\n");
sub.put("\r", "\\\\r");
sub.put("\t", "\\\\t");
StringBuffer result = new StringBuffer();
Pattern regex = Pattern.compile("\\n|\\r|\\t");
Matcher matcher = regex.matcher(comment);
while (matcher.find()) {
matcher.appendReplacement(result, sub.get(matcher.group()));
}
matcher.appendTail(result);
System.out.println(result.toString());
prints
ddnfa \n \r \tdnfadsf ' \r
Why you dont use Matcher.quoteReplacement(stringToBeReplaced);?
It is a \ problem, simplify like this :
comment = comment.replaceAll("(\n|\r|\t)", "");
output :
ddnfa dnfadsf ' t
Try this..
comment.replaceAll("(\n)|(\r)|(\t)", "\n");
I want split a string like this:
C:\Program\files\images\flower.jpg
but, using the following code:
String[] tokens = s.split("\\");
String image= tokens[4];
I obtain this error:
11-07 12:47:35.960: E/AndroidRuntime(6921): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1:
try
String s="C:\\Program\\files\\images\\flower.jpg"
String[] tokens = s.split("\\\\");
In java(regex world) \ is a meta character. you should append with an extra \ or enclose it with \Q\E if you want to treat a meta character as a normal character.
below are some of the metacharacters
<([{\^-=$!|]})?*+.>
to treat any of the above listed characters as normal characters you either have to escape them with '\' or enclose them around \Q\E
like:
\\\\ or \\Q\\\\E
You need to split with \\\\, because the original string should have \\. Try it yourself with the following test case:
#Test
public void split(){
String s = "C:\\Program\\files\\images\\flower.jpg";
String[] tokens = s.split("\\\\");
String image= tokens[4];
assertEquals("flower.jpg",image);
}
There is 2 levels of interpreting the string, first the language parser makes it "\", and that's what the regex engine sees and it's invalid because it's an escape sequence without the character to escape.
So you need to use s.split("\\\\"), so that the regex engine sees \\, which in turn means a literal \.
If you are defining that string in a string literal, you must escape the backslashes there as well:
String s = "C:\\Program\\files\\images\\flower.jpg";
String[] tokens=s.split("\\\\");
Try this:
String s = "C:/Program/files/images/flower.jpg";
String[] tokens = s.split("/");
enter code hereString image= tokens[4];
Your original input text should be
C:\\Program\\files\\images\\flower.jpg
instead of
C:\Program\files\images\flower.jpg
This works,
public static void main(String[] args) {
String str = "C:\\Program\\files\\images\\flower.jpg";
str = str.replace("\\".toCharArray()[0], "/".toCharArray()[0]);
System.out.println(str);
String[] tokens = str.split("/");
System.out.println(tokens[4]);
}