\\S 或 \\s 正则表达式将 TAB 字符匹配为单个 space 而不是 4 spaces
\\S or \\s regex matches TAB character as single space rather than 4 spaces
String s[] = {"\s","\S"};
for (int i=0;i<s.length;i++)
{
System.out.println("");
Pattern p2 = Pattern.compile(s[i]);
String tobeMatched = "sabc" + "\t" + "\t"+"abc dfg";
Matcher m2 = p2.matcher(tobeMatched);
System.out.println("expression:" + m2.pattern());
System.out.println(tobeMatched);
System.out.println("012345678901234567890123456789");
System.out.print("Position found:");
while (m2.find())
{
System.out.print(m2.start()); System.out.print(" ");
}
}
如果您看到下面的输出 - 当您打印 tobeSearched 字符串时,TAB 字符需要 4 space 秒,但是 matcher.find() returns 只有 1 space TAB 和第二个 TAB 在位置 5 返回。我期待 spaces 包括 TAB 被 matcher.start() 在位置 4,8 和 9 找到。
谁能解释一下 matcher.find() 和 matcher.start() 在这里为 TAB 字符使用的逻辑。
输出
expression:\s
sabc abc dfg
012345678901234567890123456789
Position found:4 5 9
expression:\S
sabc abc dfg
012345678901234567890123456789
Position found:0 1 2 3 6 7 8 10 11 12
我想你误解了\s。
\s 不代表 "space",而是代表 "whitespace" 个字符。
Space和制表符都是一个白色的space字符。
在 ASCII 中,space 具有字符代码 0x20,制表符具有 0x0b。
String s[] = {"\s","\S"};
for (int i=0;i<s.length;i++)
{
System.out.println("");
Pattern p2 = Pattern.compile(s[i]);
String tobeMatched = "sabc" + "\t" + "\t"+"abc dfg";
Matcher m2 = p2.matcher(tobeMatched);
System.out.println("expression:" + m2.pattern());
System.out.println(tobeMatched);
System.out.println("012345678901234567890123456789");
System.out.print("Position found:");
while (m2.find())
{
System.out.print(m2.start()); System.out.print(" ");
}
}
如果您看到下面的输出 - 当您打印 tobeSearched 字符串时,TAB 字符需要 4 space 秒,但是 matcher.find() returns 只有 1 space TAB 和第二个 TAB 在位置 5 返回。我期待 spaces 包括 TAB 被 matcher.start() 在位置 4,8 和 9 找到。
谁能解释一下 matcher.find() 和 matcher.start() 在这里为 TAB 字符使用的逻辑。
输出
expression:\s
sabc abc dfg
012345678901234567890123456789
Position found:4 5 9
expression:\S
sabc abc dfg
012345678901234567890123456789
Position found:0 1 2 3 6 7 8 10 11 12
我想你误解了\s。 \s 不代表 "space",而是代表 "whitespace" 个字符。
Space和制表符都是一个白色的space字符。 在 ASCII 中,space 具有字符代码 0x20,制表符具有 0x0b。