Java Reference
In-Depth Information
Noncompliant Code Example (String Literal)
This noncompliant code example defines a method, splitWords() , that finds matches
between the string literal ( WORDS ) and the input sequence. It is expected that WORDS would
hold the escape sequence for matching a word boundary. However, the Java compiler
treats the "\b" literal as a Java escape sequence, and the string WORDS silently compiles to
a regular expression that checks for a single backspace character.
Click here to view code image
public class Splitter {
// Interpreted as backspace
// Fails to split on word boundaries
private final String WORDS = "\b";
public String[] splitWords(String input){
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
Compliant Solution (String Literal)
This compliant solution shows the correctly escaped value of the string literal WORDS that
results in a regular expression designed to split on word boundaries:
Click here to view code image
public class Splitter {
// Interpreted as two chars, '\' and 'b'
// Correctly splits on word boundaries
private final String WORDS = "\\b";
public String[] split(String input){
Pattern pattern = Pattern.compile(WORDS);
String[] input_array = pattern.split(input);
return input_array;
}
}
Search WWH ::




Custom Search