简体   繁体   中英

Run-time error in .split(“|”)

I'm using that method in that line:

f.getCmbAttori().getSelectedItem().toString().split("|")

with an input like "13|Il Signore degli Anelli" and insted of return:

f.getCmbAttori().getSelectedItem().toString().split("|")[0] = "13"
f.getCmbAttori().getSelectedItem().toString().split("|")[1] = "Il Signore degli Anelli"

It returns an array where every character is alone, like this:

    f.getCmbAttori().getSelectedItem().toString().split("|")[0] = ""
    f.getCmbAttori().getSelectedItem().toString().split("|")[1] = "1"
    f.getCmbAttori().getSelectedItem().toString().split("|")[2] = "3"
    f.getCmbAttori().getSelectedItem().toString().split("|")[3] = "|"
    f.getCmbAttori().getSelectedItem().toString().split("|")[4] = "I"
    f.getCmbAttori().getSelectedItem().toString().split("|")[5] = "l"
[...]

    f.getCmbAttori().getSelectedItem().toString().split("|")[25] = "l"
    f.getCmbAttori().getSelectedItem().toString().split("|")[26] = "i"

How can be possible that? I'm wrinting this method in a wrong way? Here a piece of code where I use that:

PreparedStatement stmSql = null;
                 int risultato = 0;                  
                 stmSql = f.conn.prepareStatement("insert into recita (CodAttore, CodFilm) values (?, ?)");
                 stmSql.setInt(1, Integer.parseInt(f.getCmbAttori().getSelectedItem().toString().split("|")[1]));
                 stmSql.setInt(2, Integer.parseInt(f.getCmbFilmRecita().getSelectedItem().toString().split("|")[1]));
                 risultato = stmSql.executeUpdate();

The String.split function takes a regex, try using this:

split("\\|")

this will make it split on a literal |

通常,如果要按固定字符串(而不是正则表达式)分割,请使用quote

.split(Pattern.quote("|"))

Try split("\\\\|");

OR You can use

split(Pattern.quote("|"));

java.lang.String.split splits on regular expressions.

Twelve characters have special meanings in regular expressions: the backslash \\ , the caret ^ , the dollar sign $ , the period or dot . , the vertical bar or pipe symbol | , the question mark ? , the asterisk or star * , the plus sign + , the opening parenthesis ( , the closing parenthesis ) , the opening square bracket [ , and the opening curly brace { .

These special characters are often called "metacharacters" .

For More

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM