Java 如何从字节[]获取字符串及其行位置
假设我有一个如下所示的字符串:Java 如何从字节[]获取字符串及其行位置,java,regex,Java,Regex,假设我有一个如下所示的字符串: static String MSG = "4: \n"+ ":xx:xyz\n"+ ":xx:abcdef\n"+ ":xx:axvavsba\n"+ ":xx:/000000000000\n"+ ":xxs:/abcssd\n"+ "efg\n"+ "ijk\n"+ "lmn\n"+ "pqr\n"+
static String MSG = "4: \n"+
":xx:xyz\n"+
":xx:abcdef\n"+
":xx:axvavsba\n"+
":xx:/000000000000\n"+
":xxs:/abcssd\n"+
"efg\n"+
"ijk\n"+
"lmn\n"+
"pqr\n"+
":xx:asasasasas";
从这里我想转换成
byte[] messageBytes = MSG.getBytes("utf-8");
从messageBytes
中,我想根据位置及其行号提取字符串
例如,如果我给出extract(startIndex,endIndex)
它应该返回该位置的原始字符串及其行号
这里我引用的行号是::
ref中的每个字符串都指向一个行号
我试着用
String str = new String(ArrayUtils.subarray(messageByte, startIndex, endIndex), "utf-8");
我可以检索字符串,但如何提取相应的行号
我们将感谢您在这方面的任何帮助
这样做的目的是因为字符串可能包含一些日语
字符,因此如果我将应用正则表达式
,那么我将无法获得确切的字符串,以便完成我尝试此方法的相同工作
任何建议或新方法都很好。示例代码
输出
细节
公共静态信息findStringAndPosition(字符串输入){
Informations infos=新信息();
字符串[]行=input.split(“\n”);
Pattern p=Pattern.compile(“^:([^:]+):.*$”;
匹配器m=p.Matcher(“”);
int lineNumber=0;
用于(字符串行:行){
lineNumber++;
m、 重置(行);
if(m.find()){
信息添加(新信息(行号,m.group(1));
}
}
返回信息;
}
静态类信息扩展了ArrayList{
私有静态最终长serialVersionUID=-2872174623287128687L;
@凌驾
公共字符串toString(){
StringBuilder sb=新的StringBuilder();
用于(信息:此){
sb.append(String.format(“%s”位于第%s行\n)、info.getString()、info.getPosition());
}
使某人返回字符串();
}
}
静态类信息{
私有字符串;
私人职位;
公共信息(整数位置、字符串){
this.string=string;
这个位置=位置;
}
公共最终字符串getString(){
返回字符串;
}
公共最终int getPosition(){
返回位置;
}
}
startIndex和endIndex的确切含义是什么?字节位置?字符位置?绳子的长度?可能是一条线的一部分?请记住,单个字符的字节数在utf-8中是可变的。大多数是1字节,重音字符通常是2字节,但我认为它们可以超过2字节。你最好使用UTF-16,因为你知道每个字符是2字节,你可以随机“跳转”到每个偶数位置,并确保一个字符从那里开始。在UTF-8中,您可能会在字符的第二个字节的位置。startindex和endIndex基本上用于字节位置
System.out.println(findStringAndPosition(MSG));
xx found at line 2
xx found at line 3
xx found at line 4
xx found at line 5
xxs found at line 6
xx found at line 11
public static Informations findStringAndPosition(String input) {
Informations infos = new Informations();
String[] lines = input.split("\n");
Pattern p = Pattern.compile("^:([^:]+):.*$");
Matcher m = p.matcher("");
int lineNumber = 0;
for (String line : lines) {
lineNumber++;
m.reset(line);
if (m.find()) {
infos.add(new Info(lineNumber, m.group(1)));
}
}
return infos;
}
static class Informations extends ArrayList<Info> {
private static final long serialVersionUID = -2872174623287128687L;
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Info info : this) {
sb.append(String.format("%s found at line %s\n", info.getString(), info.getPosition()));
}
return sb.toString();
}
}
static class Info {
private String string;
private int position;
public Info(int position, String string) {
this.string = string;
this.position = position;
}
public final String getString() {
return string;
}
public final int getPosition() {
return position;
}
}