String should not contain java regex meta character like \d,\D all..
How we can handle programatically. It can contain *, . ? , + but not the java regex metacharacter.
public static void main(String[] args) throws Exception {
String s="\\d\\D";
if(s.contains("\\d")||s.contains("\\D")||s.contains("\\w"))
{
System.out.println("Should Not Contain");
}
}
Something like this...
O/p : Should Not Contain
Maybe you are looking for Pattern#quote. It returns a String with escaped regex special character for use as literal.
You can also use Matcher#quoteReplacement to escape special characters in a String that is intended to be used as replacement.
Are you looking for escape characters in Java so you can write \d and \D in a string? ("\d" and "\D").
See also:
http://docs.oracle.com/javase/tutorial/java/data/characters.html
What are all the escape characters in Java?
Related
I am trying to write a simple regular expression to identify all filenames in a list which end with ".req.copied" extension. The code I am using is given below
public class Regextest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String test1=new String("abcd.req.copied");
if(test1.matches("(req.copied)?")) {
System.out.println("Matches");
}
else
System.out.println("Does not Match");
}
}
The regex tests ok in online regex testers but does not function in the program. I have tried multiple combinations (like splitting req and copied into two regexes, or literal matching of the dot character) but nothing works (even the simplest regex of (reg)? returned a "Does not Match" output). Please let me know how to tackle this.
Main problem with matches here is that it requires from regex to match entire string. But in your case your regex describes only part of it.
If you really want to use matches here your code could look more like
test1.matches(".*\\.req\\.copied")
. represents any character (except line separators like \r) so if you want it to represent only dot you need to escape it like \. (in string we need to write it as "\\." because \ has also special meaning there - like creating special characters \r \n \t and so on - so it also requires escaping via additional \).
.* will let regex accept any characters before .req.copied
But in your case you should simply use endsWith method
test1.endsWith(".req.copied")
As resueman said in the comments, you don't need a regex for that. You can simply check if each filename endsWith(".req.copied").
if(test1.endsWith(".req.copied")){
System.out.println("Matches");
}else{
System.out.println("Does not match");
}
By the way, the above if-else can be replaced with System.out.println(test1.endsWith(".req.copied") ? "Matches" : "Does not match");.
test1.matches(".*\\.req\\.copied") should do it but in your case you should consider using endsWith() instead of matches.
You should come up with a Regex that would match the whole string format, not a snippet:
String test1= "abcd.req.copied";
if(test1.matches("^.*req\\.copied$")) {
System.out.println("Matches");
} else {
System.out.println("Does not Match");
}
Also, your format was using (req.copied)?, which would match any case. Also, . symbol matches any character, so escape it for matching a dot.
import java.util.StringTokenizer;
class MySplit
{
public static void main(String S[])
{
String settings = "12312$12121";
StringTokenizer splitedArray = new StringTokenizer(settings,"$");
String splitedArray1[] = settings.split("$");
System.out.println(splitedArray1[0]);
while(splitedArray.hasMoreElements())
System.out.println(splitedArray.nextToken().toString());
}
}
In above example if i am splitting string using $, then it is not working fine and if i am splitting with other symbol then it is working fine.
Why it is, if it support only regex expression then why it is working fine for :, ,, ; etc symbols.
$ has a special meaning in regex, and since String#split takes a regex as an argument, the $ is not interpreted as the string "$", but as the special meta character $. One sexy solution is:
settings.split(Pattern.quote("$"))
Pattern#quote:
Returns a literal pattern String for the specified String.
... The other solution would be escaping $, by adding \\:
settings.split("\\$")
Important note: It's extremely important to check that you actually got element(s) in the resulted array.
When you do splitedArray1[0], you could get ArrayIndexOutOfBoundsException if there's no $ symbol. I would add:
if (splitedArray1.length == 0) {
// return or do whatever you want
// except accessing the array
}
If you take a look at the Java docs you could see that the split method take a regex as parameter, so you have to write a regular expression not a simple character.
In regex $ has a specific meaning, so you have to escape it this way:
settings.split("\\$");
The problem is that the split(String str) method expects str to be a valid regular expression. The characters you have mentioned are special characters in regular expression syntax and thus perform a special operation.
To make the regular expression engine take them literally, you would need to escape them like so:
.split("\\$")
Thus given this:
String str = "This is 1st string.$This is the second string";
for(String string : str.split("\\$"))
System.out.println(string);
You end up with this:
This is 1st string.
This is the second strin
Dollar symbol $ is a special character in Java regex. You have to escape it so as to get it working like this:
settings.split("\\$");
From the String.split docs:
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
On a side note:
Have a look at the Pattern class which will give you an idea as to which all characters you need to escape.
Because $ is a special character used in Regular Expressions which indicate the beginning of an expression.
You should escape it using the escape sequence \$ and in case of Java it should be \$
Hope that helps.
Cheers
This question already has answers here:
Split string with dot as delimiter
(13 answers)
Closed 8 years ago.
I wanna split the content of a string variable, but I wanna use the point as a delimiting regular expression, my code doesn't work.
public class Test {
public static void main(String [] a){
String ch = "r.a.c.h.i.d";
String[] tab;
tab=ch.split(".");
System.out.println(tab.length);
for(String e : tab)System.out.println(e);
}
}
Change tab=ch.split("."); to tab=ch.split("\\.");. You need to escape the dot because otherwise it's treated as a special character in the regex passed to split.
tab = ch.split("\\.");
One slash is the escape character for the regex. But in Java you need to have a second slash because you have to escape the first slash.
Yes, it's possible. In a regular expression, . means any character.
Predefined character classes
. Any character (may or may not match line terminators)
So you must escape it to provide the literal . meaning. Escape it with a backslash character, providing two backslashes, because Java needs the backslash character itself escaped.
Use the regular expression "\\.".
In general, to get the literal characters out of an expression that may contain special-meaning characters, you can use the Pattern.quote method.
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.
split(Pattern.quote("."))
I need to escape quotes from a string before printing them out.
I've written a function, using char arrays to be as explicit as possible. But all this function seems to do is print out its own input:
public static String escapeQuotes(String myString) {
char[] quote=new char[]{'"'};
char[] escapedQuote=new char[]{'\\' , '"'};
return myString.replaceAll(new String(quote), new String(escapedQuote));
}
public static void main(String[] args) throws Exception {
System.out.println("asd\"");
System.out.println(escapeQuotes("asd\""));
}
I would expect the output of this to be:
asd"
asd\"
However what I get is:
asd"
asd"
Any ideas how to do this properly?
Thanks
I would try replace instead of replaceAll. The second version is designed for regex, AFAIK.
edit
From replaceAll docs
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string
So, backslash in second argument is being a problem.
The direct link to the docs
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
Java comes with readily available methods for escaping regexs and replacements:
public static String escapeQuotes(String myString) {
return myString.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("\\\""));
}
You also need to escape \ into \\ Otherwise any \ in your original string will remain \ and the parser, thinking that a special character (e.g. ") must follow a \ will get confused.
Every \ or " character you put into a Java literal string needs to be preceeded by \.
You want to use replace not replaceAll as the former deals with strings, the latter with regexps. Regexps will be slower in your case and will require even more backslashes.
replace which works with CharSequences i.e. Strings in this case exists from Java 1.5 onwards.
myString = myString.replace("\\", "\\\\");
myString = myString.replace("\"", "\\\"");
I read from a lot of webpage (for example: http://www.wellho.net/regex/java.html), they all mentioned that \s could represent any space charactor. But when I use \s in Java, it is not an eligible expression.
Anyone know the reason?
Backslashes inside strings need to be quoted in order to work.
For example, the following works fine:
public class testprog {
public static void main(String args[]) {
String s = "Hello there";
System.out.println (s.matches(".*\\s.*"));
}
}
outputting:
true
If you use a string like "\s", you should get an error along the lines of:
Invalid escape sequence - valid ones are \b \t \n \f \r \" \' \\
from your compiler since \s is not a valid escape sequence (for strings, I mean, not regexes).