1

假设我有以下以 开头的内容needle,忽略前导空格:

String haystack = "needle#####^&%#$^%...";
String haystackWithSpace = "    needle******!@@#!@@%@%!$...";

我想捕获以needleor开头的任何内容^\s*needle.*(如果允许使用正则表达式)。有没有一种优雅的方式来做到这一点而无需调用trim()?或者有没有办法让正则表达式在这里工作?我希望以下是真的:

haystackWithSpace.startsWith("needle"); // doesn't ignore leading whitespace
haystackWithSpace.startsWith("^\\s*needle"); // doesn't work

基本上,是否有s满足以下条件的字符串?:

haystack.startsWith(s) == haystackWithSpace.startsWith(s);
4

3 回答 3

4

修剪前导和尾随空格的最简单方法

string=string.trim();
于 2013-09-14T00:17:23.577 回答
4

尝试:

s.matches("^\\\\s*" + Pattern.quote("string I'm matching"))

或预编译模式:

Pattern p = Pattern.compile("^\\\\s*" + Pattern.quote("string I'm matching"));
if (p.matcher(s).matches()) { ... }
于 2013-09-14T00:19:20.750 回答
0

如果将正则表达式替换为^\s+""将从字符串开头删除所有空格。

haystack = haystack.replaceAll("^\\s+", "");
于 2013-09-14T00:16:32.433 回答