PNS
PNS

Reputation: 19905

Text search without spaces

In a text file, with variable spaces among words, is there a significantly better way of searching for and matching a given sentence?

For example, if the text file contains the following phrase with the spacing (space and tab characters) as follows

Java   is a\t\tgreat     programming\tlanguage.

what would be the most efficient way of matching it, given the input words?

An obvious approach would be to strip (or ignore) spaces and match sequences of non-whitespace characters, which can be done with standard Java I/O and string manipulation features.

Upvotes: 1

Views: 589

Answers (1)

Bart Barnard
Bart Barnard

Reputation: 1168

Just using \\s (short for [ \t\n\x0b\r\f]) for matching any whitespace?

final String str="Java   is a\t\tgreat     programming\tlanguage.";
final String pattern = "Java\\s+is\\s+a\\s+great\\s+programming\\s+language.";
Pattern pat = Pattern.compile(pattern);
Matcher match = pat.matcher(str);
if (match.find()) {
  System.out.println("Found");
}

Upvotes: 1

Related Questions