有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java模式。compile()无法从对象获取正则表达式字符串

我正在尝试使用正则表达式来查看url是否符合我为其设置的标准。我的问题是,我希望事先定义正则表达式(在前端),并将其保存在aan对象中。我怀疑这就是它出错的地方,它将无法正确编译模式。让我举个例子:

String url = "https://www.website-example.com/regex/80243/somemorechars"

if (Pattern.compile("regex/\\d{5}").matcher(url).find()) {
    System.out.println("Url found");
}

上面的例子将打印“找到Url”,不会有任何问题。 现在来看一个给我带来问题的例子:

// Imagine the below object that will be created at my Angular frontend, send to the backend and saved:

@Entity()
@Table(name = "REGEXOBJ")
public class RegexObj{

    @Id
    @GeneratedValue(generator = "regex_gen")
    @TableGenerator(name = "regex_gen", table = "ama_sequence", pkColumnValue = "Regex")
    @Column(name = "ID")
    private Long id;

    // some other fields I need

    @Column(name = "REGEX", nullable = false)
    private String regex;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    // getters and setters for the other fields

    public String getRegex() {
        return regex;
    }

    public void setRegex(String regex) {
        this.regex = regex;
    }
}
// =================================================== //

public boolean checkUrl(RegexObj regexObj) {
    String url = "https://www.website-example.com/regex/80243/somemorechars"

    if (Pattern.compile(regexObj.getRegex()).matcher(url).find()) {
        System.out.println("Url found");
    }
}

现在,url将不会与正则表达式匹配,可能是因为字符串是“扁平”的,“\\d{5}”部分将不再被视为正则表达式。有没有办法解决这个问题

编辑-添加了我使用的类的简化版本


共 (1) 个答案

  1. # 1 楼答案

    我解决了这个问题。问题实际上是在保存从前端发送的对象时发生的。我通过前端的输入字段将字符串设置为“regex/\\\d{5}”,它被保存为“regex/\\\\d{5}”。在我的输入字段中将其更改为“regex/\d{5}”,解决了这个问题