JSP JSTL函数fn:split无法正常工作

问题描述 投票:1回答:1

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

我试图使用JSTL fn:split函数拆分字符串,同样,

<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.

任何帮助真的很感激!!

java jsp split jstl
1个回答
1
投票

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它说:

为指定的字符串构造字符串标记生成器。 delim参数中的字符是用于分隔标记的分隔符。分隔符字符本身不会被视为令牌。

How `fn:split` exactly work?

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

abc~$pqr$xyz
   ^^   ^

第一次拆分:

abc
$pqr$xyz

第二次分裂:

abc
pqr$xyz

分割宽度:

abc
pqr
xyz

在Servlet中使用split而不是JSTL

例如 :

String[] array = "abc~$pqr$xyz".split("~\\$");
© www.soinside.com 2019 - 2024. All rights reserved.