How to check weather string contains backslash? - java

I want to check if a string contains "\" or not. I used the string method contains(), but its not working
String path = "D:\steve\";
if(path.contains("\"){
path = path.replaceAll("\\\\","");
}

Use escape character \
public class test{
public static void main(String[] args) {
String str = "a\\b";
System.out.println(str.contains("\\"));
}
}
A character preceded by a backslash (\) is an escape sequence and has
special meaning to the compiler.
https://docs.oracle.com/javase/tutorial/java/data/characters.html

Related

Regular expression match on online tool does not match in Java when there is a special character at the end

I have following regular expression
(?i)\b((https?:\/\/www\.)|(https?:\/\/)|(www\.))?(localhost).*\b
and following url
http://localhost:8081/saman/ab/cde/fgh/ijkl.jsf?gdi=ff8081abcdef02a011b0af032170001&ci=
It matches when tried with both https://regex101.com/ and http://rubular.com/r/kyiKS9OlsM
But when there is any special character at the end, url does not match
import java.text.Format;
import java.text.MessageFormat;
import java.util.regex.Pattern;
public class JavaApplication1 {
/**
* #param args the command line arguments
*/
private static final String URL_MATCH_REGEX = "(?i)\\b((https?:\\/\\/www\\.)|(https?:\\/\\/)|(www\\.))?({0}).*\\b";
private static final Format format = new MessageFormat(URL_MATCH_REGEX);
static String regex = "";
static String url = "http://localhost:8081/saman/ab/cde/fgh/ijkl.jsf?gdi=ff8081abcdef02a011b0af032170001&ci=";
public static void main(String[] args) {
try {
regex = format.format(new Object[]{replaceDomainToUseInRegex("localhost")});
System.out.println(regex);
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher( url ).matches());
} catch (Exception e) {
}
}
private static String replaceDomainToUseInRegex(String domain) {
return domain.replace(".", "\\.").replace("/", "\\/").replace("?", "\\?");
}
}
Can anyone help me to figure out the issue here?
Your problem is that you're using two different kinds of matches. Java's matches() requires the entire string to match the regular expression. regex101.com does not. So it says there's a match if any substring of your input string matches the regex. However, in regex101.com, you can get the same kind of match by putting ^ in the front of the regex and $ at the end; now it requires the entire string to match. And it doesn't match.
(\b matches a "word boundary"; it matches the "zero-width substring" between a non-word character and a word character (in either order), or between a word character and the beginning or end of the string. = is not a word character, thus \b doesn't match the position between = and the end of the string.)

Java backslash split string

I have a string in the format like "test\00216243".
I need to split the string in Java based on the backslash '\' .
My Program:
public class StringTest {
public static void main(String[] args) {
String taskOwner = "test\00216243";
String taskArray[] = taskOwner.split(Pattern.quote(System.getProperty("file.separator")));
System.out.println(taskArray[0]);
}
}
When i run this program i am getting the following result but not the result as 'test'. Any help?
Result:
test16243
Just to add on
\ is a special character in regular expressions, as well as in Java string literals. If you want a literal backslash in a regex, you have to double it twice.
When you type "\\", this is actually a single backslash (due to escaping special characters in Java Strings).
Regular expressions also use backslash as special character, and you need to escape it with another backslash. So in the end, you need to pass "\\" as pattern to match a single backslash.
public static void main(String[] args) {
String taskOwner = "test\\00216243";
String taskArray[] = taskOwner.split("\\\\");
System.out.println(taskArray[0]);
}
output
test
00216243
\002 represents a unicode character. SO i suggest you to split your input according to the character other than alphabet or digit.
String string1 = "test\00216243";
String part[] = string1.split("[^a-z0-9]");
System.out.println(part[0]);
Output:
test
String "test\00216243" should be replaced with "test\\00216243"
Because \ represent the escape sequence, you need to use \\ in the string to represent a \
Try this
public static void main(String[] args) {
String taskOwner = "test\\00216243";
String myarray[] = taskOwner.split("\\\\");
System.out.println(myarray[0]+" "+myarray[1]);
}
Output
test 00216243
Reference:
How to split a java string at backslash

Boundary Java regex does not work

Could you please tell me why this expression does not return TRUE?
public class test {
public static void main(String[] args) throws IOException{
String str = "The dog plays";
boolean t = str.matches("\\bdog\\b");
System.out.println(t);
}
}
matches method will always try to match the whole string. It won't be a suitable method for matching a particular string. So change your regex to,
".*\\bdog\\b.*"
in-order to make the matches method to return true.
String str = "dog plays";
System.out.println(str.matches(".*\\bdog\\b.*"));
Output:
true
\b called word boundary which matches between a word character and a non-word character. Note that the above regex will match also the string foo:dog:bar. If you want the dog to be a separate word , i suggest you to use this regex.
".*(?<!\\S)dog(?!\\S).*"
Example:
System.out.println("dog plays".matches(".*(?<!\\S)dog(?!\\S).*"));
System.out.println("foo:dog:bar".matches(".*(?<!\\S)dog(?!\\S).*"));
Output:
true
false
For the Matcherclass:
matches() returns true if the entire string matches the expression
find() returns true if any subsequence of the string matches the expression.
So it's likely that this is what you want:
public class Test {
public static void main(String[] args) {
String str = "The dog plays";
boolean t = str.find("\\bdog\\b");
System.out.println(t);
}
}

Java regular expression: Matches back slash character

How to macth a backslah (\) in java regular expression? I hava some sript to matching all latex tag In some file but it didnt work.
public class TestMatchTag {
public static void main(String[] args) {
String tag = "\begin";
if (Pattern.matches("\\\\[a-z]+", tag)) {
System.out.println("MATCH");
}
}
}
Replace String tag = "\begin"; with String tag = "\\begin";. The regex is valid, but your input string needs to escape \ character.
Try this,
Pattern.matches("[\\a-z]+", tag)
You need another backslash to escape the "\" in "\begin", change it to "\begin", otherwise the "\b" in your "\begin" will be considered as one character.
This should work...
Pattern.matches("\\[a-z]+", tag);
[a-z] allows any character between a-z more than once and \\ allows "\" once.
you can validate your expression online here

Avoid overwriting files using regex

I have a class that replaces illegal characters that strings might contain to allow using them as filenames. The problem is that it replaces any illegal character with "_", which is fine as long as the string does not entirely consist of illegal characters.
For example cleanFilename(">>>") will return the same string cleanFilename("***") returns. So storing "***" in a file after storing ">>>", would replace the first file.
public class StringCleaner {
public static String cleanFilename(String dirtyString) {
return dirtyString.replaceAll("[:\\/*?|<> ]", "_");
}
public static String cleanDirectory(String dirtyDirectory) {
return dirtyDirectory.replaceAll("[:\\*?|<> ]", "_");
}
}
What can i change in order to avoid this problem?
Sorry for the awkward title I could not find a better one.
Update: I want it to create readable filenames so that identification through reading the filename only will be possible.
Thanks
Selim
So you are looking for a reversible and repeatable mechanism for replacing funny characters in file names. A typical way to do this is to create an escape sequence. For example, consider the following:
Pick a single character to use as an escape sequence. This character must be a legal character in a file name, but not commonly used, and we will use it as an escape sequence.
Let's chose the + character. Then, we replace all illegal characters with a sequence of characters that uniquely identfy the replaced character.
For example, replacing the space (character 32) in the file "this has a space" would give the result "this+32+has+32+a+32+space" ....
public class StringCleaner {
public static void main(String[] args) {
StringCleaner sc = new StringCleaner();
System.out.println(sc.cleanFilename("this has a space"));
System.out.println(sc.cleanFilename("this has a plus +"));
System.out.println(sc.cleanFilename("this is full :\\/*?|<> + of stuff"));
}
private static final Pattern illegalfilechars = Pattern.compile("[:\\/*?|<> +]");
private static final Pattern illegaldirchars = Pattern.compile("[:\\*?|<> +]");
private static final String replaceall(Pattern pattern, String dirtyString) {
Matcher mat = pattern.matcher(dirtyString);
if (!mat.find()) {
return dirtyString;
}
StringBuffer sb = new StringBuffer();
do {
mat.appendReplacement(sb, "+" + (int)mat.group(0).charAt(0) + "+");
} while (mat.find());
mat.appendTail(sb);
return sb.toString();
}
public static String cleanFilename(String dirtyString) {
return replaceall(illegalfilechars, dirtyString);
}
public static String cleanDirectory(String dirtyDirectory) {
return replaceall(illegaldirchars, dirtyDirectory);
}
}
When I run the code I get the results:
this+32+has+32+a+32+space
this+32+has+32+a+32+plus+32++43+
this+32+is+32+full+32++58+\+47++42++63++124++60++62++32++43++32+of+32+stuff
which also indicates that the pattern is wrong for the character '\'

Categories