首页 > 解决方案 > RichTextFX 注释和属性正则表达式

问题描述

我正在尝试使用 RichTextFX 库在CodeArea. 我创建了一些正则表达式用于注释以及尝试将样式设置为CodeArea. 编辑:我能够让它们正常工作。除了当我向具有属性的行添加注释时。我用于确定属性的正则表达式无法判断#行首何时有 a 。#我已经尝试过,但如果它看到开头有 a,我无法让它否定其余部分。

这是我正在使用的两种模式:

Pattern COMMENT = Pattern.compile("(?<SingleLineComment>#+)(?<Comment>.*\n)");

Pattern PROPERTY = Pattern.compile("(\n?(?<PropertyName>.+)(\\h*=\\h*)(?<PropertyValue>\\S+))");

以下是它们在代码中的使用方式:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.LineNumberFactory;
import org.fxmisc.richtext.model.StyleSpans;
import org.fxmisc.richtext.model.StyleSpansBuilder;
import java.util.Collection;
import java.util.Collections;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTest extends Application
{
    public static void main (String[] args) {
        launch(args);
    }



    @Override
    public void start (Stage primaryStage) throws Exception {
        _area = new CodeArea();
        _area.getStylesheets().add(getClass().getResource("/css/settings-design.css").toExternalForm());
        _area.setParagraphGraphicFactory(LineNumberFactory.get(_area));

        _area.textProperty().addListener((obs, oldValue, newValue) -> {
            computeHighlighting(newValue);
        });

        primaryStage.setScene(new Scene(_area, 400, 600));

        primaryStage.show();

        _area.appendText(PROPERTIES);
    }

    private void computeHighlighting(String text) {
        Matcher equalsTest = COMMENT.matcher(text);
        while (equalsTest.find()){
            _area.setStyle( equalsTest.start(), equalsTest.end(), Collections.singleton("comment"));
        }

        Matcher propertyMatcher = PROPERTY.matcher(text);
        while (propertyMatcher.find()){
            _area.setStyle(propertyMatcher.start(1), propertyMatcher.end(3), Collections.singleton("property-name"));
            _area.setStyle(propertyMatcher.start(4), propertyMatcher.end(4), Collections.singleton("property-value"));
        }
    }

    private CodeArea _area;

    private static final Pattern COMMENT = Pattern.compile("(?<SingleLineComment>#+\\h*)(?<Comment>.*)\n?");
    private static final Pattern PROPERTY = Pattern.compile("(?:[#].+|(\n?(?<PropertyName>.+)(\\h*=\\h*)(?<PropertyValue>\\S+)))");

    private static final Pattern EQUALSTEST = Pattern.compile("=");

    public static final String PROPERTIES = "#Tue Nov 06 12:42:33 CST 2018\n" +
            "#prop0=true";

并且code-area.css

.comment {
    -fx-fill: #008e00;
}

.property-name {
    -fx-fill: #ff8e31;
}

.property-value {
    -fx-fill: #58a3ff;
}

预先感谢您的帮助!

标签: javaregexjavafxrichtextfx

解决方案


这是一个正则表达式,用于将属性文件行解析为 Java 抱怨的键-分隔符-值-注释部分。

^\s*(?:|(?<PropertyName>\w+(?:\.\w+)*)(?<Divider>\s*[=: ]\s*)(?<PropertyValue>\w(?:.|\\,|\\[\n\r\f\v]+)*))(?<Comment>[#!].*)?$

请注意,这个正则表达式仍然不是详尽无遗的,内置的Properties类比正则表达式更适合这个任务。(使用 load 函数来解析源代码,它基本上像 Map 一样工作)


推荐阅读