亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java正則表達式匹配UTF-8字符串(無副本)

Java正則表達式匹配UTF-8字符串(無副本)

神不在的星期二 2023-12-13 16:56:52
我正在從 SocketChannel 加載大型 UTF-8 文本,并且需要提取一些值。模式匹配java.util.regex對此非常有用,但是解碼為 Java 的 UTF-16 withCharBuffer cb = UTF_8.decode(buffer);會復制此緩沖區,使用雙倍的空間。有沒有辦法以 UTF-8 創建 CharBuffer“視圖”,或者以其他方式與字符集進行模式匹配?
查看完整描述

1 回答

?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

您可以創建輕量級CharSequence包裝ByteBuffer,無需正確的 UTF8 處理即可執行簡單的字節到字符轉換。


只要您的正則表達式僅包含 Latin1 字符,它就可以在“天真”轉換的字符串上工作。


只有與 reg ex 匹配的范圍才需要從 UTF8 正確解碼。


下面的代碼說明了這種方法。


import java.io.UnsupportedEncodingException;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.charset.Charset;

import java.util.regex.Matcher;

import java.util.regex.Pattern;


import org.junit.Test;


import junit.framework.Assert;



public class RegExSnippet {


    private static Charset UTF8 = Charset.forName("UTF8");


    @Test

    public void testByteBufferRegEx() throws UnsupportedEncodingException {


        // this UTF8 byte encoding of test string

        byte[] bytes = ("lkfmd;wmf;qmfqv amwfqwmf;c "

        + "<tag>This is some non ASCII text 'кирилицеский текст'</tag>"

        + "kjnfdlwncdlka-lksnflanvf ").getBytes(UTF8);


        ByteBuffer bb = ByteBuffer.wrap(bytes);


        ByteSeqWrapper bsw = new ByteSeqWrapper(bb);


        // pattern should contain only LATIN1 characters

        Matcher m = Pattern.compile("<tag>(.*)</tag>").matcher(bsw);


        Assert.assertTrue(m.find());


        String body = m.group(1);


        // extracted part is properly decoded as UTF8

        Assert.assertEquals("This is some non ASCII text 'кирилицеский текст'", body);

    }


    public static class ByteSeqWrapper implements CharSequence {


        final ByteBuffer buffer;


        public ByteSeqWrapper(ByteBuffer buf) {

            this.buffer = buf;

        }


        @Override

        public int length() {

            return buffer.remaining();

        }


        @Override

        public char charAt(int index) {

            return (char) (0xFF & buffer.get(index));

        }


        @Override

        public CharSequence subSequence(int start, int end) {

            ByteBuffer bb = buffer.duplicate();

            bb.position(bb.position() + start);

            bb.limit(bb.position() + (end - start));

            return new ByteSeqWrapper(bb);

        }


        @Override

        public String toString() {

            // a little hack to apply proper encoding

            // to a parts extracted by matcher

            CharBuffer cb = UTF8.decode(buffer);

            return cb.toString();

        }

    }

}


查看完整回答
反對 回復 2023-12-13
  • 1 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號