Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-如何编写包含给定集合变量析取的正则表达式_Java_Regex_Map_Set_Information Retrieval - Fatal编程技术网

Java-如何编写包含给定集合变量析取的正则表达式

Java-如何编写包含给定集合变量析取的正则表达式,java,regex,map,set,information-retrieval,Java,Regex,Map,Set,Information Retrieval,我需要检索一些特定单位后面的数字,例如10米,5公里。。。从给定的网页。这些特定单位是地图的键keySet()返回逗号分隔的列表,如[“m”、“km”…]。有没有一种聪明的方法可以将集合作为变量的析取,比如[“m”|“km”|…],这样我就可以在正则表达式中使用它,例如: "(\\d+)"+ " " +"myMap.keySet()......" 使用管道连接集合: “(\\d+)\\s*(“+StringUtils.join(myMap.keySet(),“|”)+””您可以尝试以下方法:

我需要检索一些特定单位后面的数字,例如10米,5公里。。。从给定的网页。这些特定单位是
地图的键
keySet()
返回逗号分隔的列表,如
[“m”、“km”…]
。有没有一种聪明的方法可以将集合作为变量的析取,比如
[“m”|“km”|…]
,这样我就可以在正则表达式中使用它,例如:

"(\\d+)"+ " " +"myMap.keySet()......"
使用管道连接集合:
“(\\d+)\\s*(“+StringUtils.join(myMap.keySet(),“|”)+””
您可以尝试以下方法:

String p = "\\d+ (?:";
for (String key : yourMap.keySet())
   p += key + "|";
p = p.substring(0, p.length() - 1) + ")";
怎么样

myMap.keySet().toString().replaceAll(",\\s*", "|").replaceAll("^\\[|\\]$", "")
//                       ^                         ^
//                       |                         +remove [ at start and ] at end
//                       +replace `,` and spaces after it with |
反而

myMap.keySet()
您的代码可以如下所示

String data = "1km is equal 1000 m, and 1  m is equal 100cm. 1 mango shouldnt be found";

Map<String, Integer> map = new HashMap<>();
map.put("m", 1);
map.put("km", 2);
map.put("cm", 3);

String regex = "\\d+\\s*("
        + map.keySet().toString()       //will create "[cm, m, km]"
            .replaceAll(",\\s*", "|")   //will change it to "[cm|m|km]"
            .replaceAll("^\\[|\\]$", "")//will change it to "cm|m|km"
        + ")\\b";                       
    // I added \\b - word boundary - to prevent matching `m` if it is at
    // start of some word like in 1 mango where it normally would match
    // (1 m)ango

Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(data);
while(m.find()){
    System.out.println(m.group());
}
String data=“1公里等于1000米,1米等于100厘米,不应该找到1个芒果”;
Map Map=newhashmap();
地图放置(“m”,1);
地图放置(“km”,2);
地图放置(“cm”,3);
字符串regex=“\\d+\\s*(”
+map.keySet().toString()//将创建“[cm,m,km]”
.replaceAll(“,\\s*”,“|”)将其更改为“[cm | m | km]”
.replaceAll(“^\\[\\]$”,“”)//将其更改为“cm | m | km”
+“)\\b”;
//我添加了\\b-单词边界-以防止在
//某个单词的开头,如1芒果,通常与之匹配
//(1米)安戈
Pattern p=Pattern.compile(regex);
匹配器m=p.Matcher(数据);
while(m.find()){
System.out.println(m.group());
}

不清楚您想做什么。您能给出一些相同的输入和输出吗?您还想在匹配中包含单位,还是只包含跟在这些单位后面的数字?在Map实例上调用的
keySet()
的结果已设置,并且集合在Java中没有
join
方法。@Pshemo:对不起,我没有意识到这一点。我已将解决方案更新为使用StringUtils。这样行吗?