简体   繁体   English

从 RegEx String 获取资源

[英]Get resource from RegEx String

After hours of searching and trying and failing, I decided to ask my question here.经过数小时的搜索、尝试和失败,我决定在这里提出我的问题。 I want to replace :(.+?): in a string with the resource loaded from /src.我想用从 /src 加载的资源替换字符串中的:(.+?): For example if I would type in ":foo.bar:" it would replace it with this.getClass().getResource("foo.bar");例如,如果我输入“:foo.bar:”,它将用 this.getClass this.getClass().getResource("foo.bar");替换它this.getClass().getResource("foo.bar"); . .

My concrete situation: I have a little chat application using smileys, located in the "smileys"-folder in "src".我的具体情况:我有一个使用笑脸的小聊天应用程序,位于“src”中的“smileys”文件夹中。 If a user types ":foo:", it should get the full URL of "smileys/foo.png", if the file exists ( this.getClass().getResource("smileys/foo.png"); in this case) and put it into tags.如果用户输入“:foo:”,它应该得到“smileys/foo.png”的完整URL,如果文件存在( this.getClass().getResource("smileys/foo.png");在这种情况下) 并将其放入标签中。 So for example if a user types "foo :bar:", it should be converted into "foo C:/<...>/smileys/bar.png".因此,例如,如果用户键入“foo :bar:”,则应将其转换为“foo C:/<...>/smileys/bar.png”。

How could I do this?我怎么能这样做? Thank you for your answers,谢谢您的回答,

Benni本尼

They explain how to do this in the documentation provided by oracle.This normally to all regex in all languages though, not just java.他们在 oracle 提供的文档中解释了如何做到这一点。这通常适用于所有语言的所有正则表达式,而不仅仅是 Java。

" A backreference is specified in the regular expression as a backslash () followed by a digit indicating the number of the group to be recalled. For example, the expression (\\d\\d) defines one capturing group matching two digits in a row, which can be recalled later in the expression via the backreference \\1. " 在正则表达式中,反向引用被指定为反斜杠 () 后跟一个数字,表示要调用的组的编号。例如,表达式 (\\d\\d) 定义了一个匹配连续两位数字的捕获组,稍后可以通过反向引用 \\1 在表达式中调用它。

To match any 2 digits, followed by the exact same two digits, you would use (\\d\\d)\\1 as the regular expression:要匹配任何 2 位数字,后跟完全相同的两位数字,您可以使用 (\\d\\d)\\1 作为正则表达式:

Enter your regex: (\d\d)\1

Enter input string to search: 1212

I found the text "1212" starting at index 0 and ending at index 4.

If you change the last two digits the match will fail:如果您更改最后两位数字,则匹配将失败:

Enter your regex: (\d\d)\1

Enter input string to search: 1234
No match found.

For nested capturing groups, backreferencing works in exactly the same way: Specify a backslash followed by the number of the group to be recalled."对于嵌套的捕获组,反向引用的工作方式完全相同:指定一个反斜杠,后跟要调用的组的编号。”

https://docs.oracle.com/javase/tutorial/essential/regex/groups.html https://docs.oracle.com/javase/tutorial/essential/regex/groups.html

Below code will do what you want:下面的代码会做你想要的:

String s = "x = :foo.bar: ;";
String res = s.replaceAll(":(.+?):","this.getClass().getResource(\"$1\")");
System.out.println(res);

prints印刷

x = this.getClass().getResource("foo.bar") ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM