ActionScript - 正規表現とTextFormatを使用してHTMLタグ間のテキストをスタイル化する

StackOverflow https://stackoverflow.com/questions/9519857

質問

whileの間にこの問題に苦しんでいます:

私はHTMLを含む文字列を持っていて、タグ間で文字を取得するために正規表現を使用しています。その後、それらの文字にTextFormatを適用しようとしています。

問題は、それが「text」プロパティの代わりにTextFieldの "HTMLText"プロパティを使用していることです(HTMLタグが表示されたくないため)。そのため、TextFormatを適用すると、正規表現から返される文字インデックスが正しくありません。

これは問題を説明するいくつかのサンプルコードです:

var txt:String = "<b>Sample</b> string with bold text";

var tf:TextField = new TextField();
addChild(tf);
tf.htmlText = txt;

var format:TextFormat = new TextFormat();
format.bold = true;

var regExp:RegExp = /<b>(.*?)<\/b>/g;
var match:Object = regExp.exec(txt);
while (match != null) {
    tf.setTextFormat(format, match.index, match.index + match[0].length);
    match = regExp.exec(txt);
}
.

これは私に与えます:

"太字の文字列"

希望の代わりに:

"太字の文字列" HTMLタグmatch[0].lengthのため、<b></b>は7文字が長すぎるためです。

これについて何をすることができますか?ありがとう!

役に立ちましたか?

解決

Using TextField.htmlText, <b> tags should give bold text, without any need for TextFormat.bold or regexp, provided you embed the right fonts (or use device fonts).

But, I know there is sometimes issues with the HTML support in TextFields in combination with font handling, and perhaps your actual situation is more complex than the example with bold text. In that case I would recommend using StyleSheet formatting instead of the regexp/TextFormat combo. Besides the problem with offset mismatch that you have encountered, I believe that combining the two different approaches to text formatting - HTML and TextFormat - runs the risk of giving other problems, while using HTML text and StyleSheet are meant to be used together.

I started writing an example of using StyleSheet/htmlText, but since <b> should work anyway, without styling, it got a bit weird, so I scratched it. But let me know if you need example code.

他のヒント

tf.setTextFormat(format, match.index, match.index + match[1].length); 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top