Regex 使用正则表达式处理需求
请参阅下面的xml文件。$BASE_DIR、$ENV_前缀等是linux操作系统中的环境变量。我想找到格式为$的变量,后跟任何字母,然后是任何字母或数字,直到标记关闭的符号,并将这些变量存储在列表中。请注意${envPrefix}稍后会被第三方api替换,在此列表中应忽略Regex 使用正则表达式处理需求,regex,Regex,请参阅下面的xml文件。$BASE_DIR、$ENV_前缀等是linux操作系统中的环境变量。我想找到格式为$的变量,后跟任何字母,然后是任何字母或数字,直到标记关闭的符号,并将这些变量存储在列表中。请注意${envPrefix}稍后会被第三方api替换,在此列表中应忽略 <?xml version="1.0" encoding="UTF-8"?> <myConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<?xml version="1.0" encoding="UTF-8"?>
<myConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://myconfig.xsd">
<configVariable name="baseDir" type="java.lang.String">
<value>$BASE_DIR</value>
</configVariable>
<configVariable name="envPrefix" type="java.lang.String">
<value>$ENV_PREFIX</value>
</configVariable>
<configVariable name="logPath" type="java.lang.String">
<value>${baseDir}/${envPrefix}</value>
</configVariable>
<configVariable name="appName">
<value>Publish</value>
</configVariable>
<configVariable name="CUSTOM_LOG">
<value>$CUSTOM_LOG</value>
</configVariable>
<configVariable name="PUBLISH_LOG">
<value>$PUBLISH_LOG</value>
</configVariable>
<logging>
<destination type="file" maxFileBackup="16" maxFileSize="10MB"
filePath="${PUBLISH_LOG}/${appName}.log" smLogName="publish" />
<priority level="info" smLogName="publish" />
</logging>
.......
</myConfig>
String fileContent="the_file_provided_above";
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile(Pattern.quote("????What goes here">)).matcher(fileContent);
while (m.find()) {
allMatches.add(m.group());
}
$BASE_DIR
$ENV_前缀
${baseDir}/${envPrefix}
发表
$CUSTOM_LOG
$PUBLISH\u日志
.......
String fileContent=“上面提供的文件”;
List allMatches=new ArrayList();
Matcher m=Pattern.compile(Pattern.quote(“???这里是什么“>)).Matcher(fileContent);
while(m.find()){
添加(m.group());
}
尝试使用以下内容作为正则表达式:
(\$\w+)
这将匹配一个文本
$
,后跟至少一个单词字符(a-z、a-z、0-9和_)。通过在$
之后匹配单词字符,我们可以避免匹配${…}
元素,因为\w
将不匹配{
我正在尝试找出需要在这里使用的正则表达式,我不确定在$之后使用什么来处理这个问题。我尝试了下面的方法只是为了让它工作…Matcher m=Pattern.compile(Pattern.quote($ENV_PREFIX)).Matcher(fileContent);而(m.find()){allMatches.add(m.group());}完美!它符合我的要求。谢谢。使用Matcher m=Pattern.compile(\\$[a-zA-Z]\\w*))。Matcher(fileContent);Matcher m=Pattern.compile(\\$[a-zA-Z]\\w*))。Matcher(fileContent);while(m.find()){String group=m.group();allMatches.add(group.substring(7,group.length()-8));}