I'm trying to use a regex to see if an url matches the criteria I have set for it. The problem I have is that I want the regex to be defined beforehand (in the frontend) and saved in aan object. I suspect that's where it goes wrong and it won't be able to compile the Pattern correctly. Let me give an example:
String url = "https://www.website-example.com/regex/80243/somemorechars"
if (Pattern.compile("regex/\\d{5}").matcher(url).find()) {
System.out.println("Url found");
}
The above example will print "Url found" and there won't be any problems. Now for the example that gives me the problems:
// 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");
}
}
Now the url won't be matched to the regex, problably because the String is 'flat' and the '\\d{5}' part won't be seen as regex anymore. Is there a way around this to make it work?
EDIT - Added a simplified version of the class I use
I fixed the issue. The problem occured in fact while saving the object that was sent from the frontend. Where I set the string as "regex/\\d{5}" via an input field at the frontend it got saved as "regex/\\\\d{5}". Changing it to "regex/\d{5}" in my input field fixed the issue!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.