JSP JSTL 函数 fn:split 工作不正常

JSP JSTL funciton fn:split is not working properly

今天,我遇到了一个问题,需要你的帮助来解决它。

我正在尝试使用 JSTL fn:split function 拆分字符串,同样,

<c:set var="stringArrayName" value="${fn:split(element, '~$')}" />

实际字符串:- "abc~$pqr$xyz"

预期结果:-

abc 
pqr$xyz

只需要 2 串部分,但它给出了

abc
pqr
xyz

这里,一共返回了3个字符串,这是错误的。

注意:- 我添加了 <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> at the top of JSP.

非常感谢任何帮助!!

JSTL 拆分不像 Java 拆分那样工作您可以从源代码中检查差异:

org.apache.taglibs.standard.functions.Functions.split

public static String[] split(String input, String delimiters) {
    String[] array;
    if (input == null) {
        input = "";
    }
    if (input.length() == 0) {
        array = new String[1];
        array[0] = "";
        return array;
    }

    if (delimiters == null) {
        delimiters = "";
    }

    StringTokenizer tok = new StringTokenizer(input, delimiters);
    int count = tok.countTokens();
    array = new String[count];
    int i = 0;
    while (tok.hasMoreTokens()) {
        array[i++] = tok.nextToken();
    }
    return array;
}

java.lang.String.split

public String[] split(String regex, int limit) {
    return Pattern.compile(regex).split(this, limit);
}

很明显 fn:split 使用 StringTokenizer

    ...
    StringTokenizer tok = new StringTokenizer(input, delimiters);
    int count = tok.countTokens();
    array = new String[count];
    int i = 0;
    while (tok.hasMoreTokens()) {
        array[i++] = tok.nextToken();
    }
    ...

不像 java.lang.String.split 那样使用 regular expression

return Pattern.compile(regex).split(this, limit);
//-----------------------^

StringTokenizer documentation 它说:

Constructs a string tokenizer for the specified string. The characters in the delim argument are the delimiters for separating tokens. Delimiter characters themselves will not be treated as tokens.

`fn:split` 究竟如何工作?

它在分隔符中的每个字符上拆分,在你的情况下你有两个字符 ~$ 所以如果你的字符串是 abc~$pqr$xyz 它会像这样拆分它:

abc~$pqr$xyz
   ^^   ^

第一次分裂:

abc
$pqr$xyz

第二次分裂:

abc
pqr$xyz

第三个分裂:

abc
pqr
xyz

解决方案

use split in your Servlet instead of JSTL

例如:

String[] array = "abc~$pqr$xyz".split("~\$");