我有这些数据
ReferenceDataLocation = as
##############################################################################
#
# LicenseKey
# Address Doctor License
#
##############################################################################
LicenseKey = al
Run Code Online (Sandbox Code Playgroud)
我想只捕获关键值对,例如:ReferenceDataLocation = as和LicenseKey = al
我写了(?xms)(^[\w]+.*?)(?=^[\w]+|\z)正则表达式,这是完美的,除了它还捕获#####部分,这不是键值对.
请帮我修改相同的正则表达式(?xms)(^[\w]+.*?)(?=^[\w]+|\z)只获得ReferenceDataLocation = as和LicenseKey = al
注意:在这里你可以试试
更新
我试过(?xms)(^[\w]+.*?)(?=^[\w^#]+|\z)它在网站上工作,但在java中给我一个错误
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 31
(?xms)(^[\w]+.*?)(?=^[\w^#]+|\Z)
^
Run Code Online (Sandbox Code Playgroud)
适用于我的Updat Regex
(?xms)(^[\w]+.*?)(?=^[\w^\s]+|\z)
Run Code Online (Sandbox Code Playgroud)
你不能用一个简单的正则表达式匹配来做到这一点.你无法解释这样的事件:
# some words here LicenseKey = al
Run Code Online (Sandbox Code Playgroud)
正则表达式引擎无法从后面LicenseKey看到行尾.Java的正则表达式引擎(无界后台)不支持此功能.
但你发布的内容看起来就像是一个属性文件.试试这个:
import java.io.FileInputStream;
import java.util.Properties;
public class Main {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
properties.load(new FileInputStream("test.properties"));
System.out.println(properties.getProperty("ReferenceDataLocation"));
System.out.println(properties.getProperty("LicenseKey"));
System.out.println(properties.getProperty("foo"));
}
}
Run Code Online (Sandbox Code Playgroud)
将打印:
as al null
请注意,您的输入文件无需调用test.properties,您可以为其指定任何名称.
如果您事先不知道密钥,则可以简单地遍历属性文件中的所有条目,如下所示:
for(Map.Entry<Object, Object> entry : properties.entrySet()) {
System.out.println(entry.getKey() + " :: " + entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)
打印:
LicenseKey :: al ReferenceDataLocation :: as
并且还Properties#stringPropertyNames()返回一个Set<String>表示属性文件中所有键的内容(有关详细信息,请参阅API文档).
看到: