Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.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
Regex 用于解析键中带有逗号和[]的键值对的正则表达式_Regex_Scala - Fatal编程技术网

Regex 用于解析键中带有逗号和[]的键值对的正则表达式

Regex 用于解析键中带有逗号和[]的键值对的正则表达式,regex,scala,Regex,Scala,我希望形成一个正则表达式来解析以下格式的字符串,并将其作为键值对分离,键值为[test,2],值为11,依此类推 [test,2]=11, [test,3]=12, [test,7]=11, [test,11]=4, [test,16]=5 一旦形成了正确的正则表达式,我就可以用这种方式将其作为键值对加载到映射中 <REGEX_PATTERN>.findAllMatchIn(input).map(m => (m.group(1).trim(), m.group(2).trim

我希望形成一个正则表达式来解析以下格式的字符串,并将其作为键值对分离,键值为[test,2],值为11,依此类推

[test,2]=11, [test,3]=12, [test,7]=11, [test,11]=4, [test,16]=5
一旦形成了正确的正则表达式,我就可以用这种方式将其作为键值对加载到映射中

<REGEX_PATTERN>.findAllMatchIn(input).map(m => (m.group(1).trim(), m.group(2).trim())).toMap
.findAllMatchIn(input).map(m=>(m.group(1.trim(),m.group(2.trim())).toMap
欣赏使用正则表达式模式的任何指针。

尝试以下模式:

val pattern = "(\\[\\w+,\\d+\\])=(\\d+)(,\\s)?"r
例如:

scala> val input = """[test,2]=11, [test,3]=12, [test,7]=11, [test,11]=4, [test,16]=5"""
input: String = [test,2]=11, [test,3]=12, [test,7]=11, [test,11]=4, [test,16]=5

scala> val pattern = "(\\[\\w+,\\d+\\])=(\\d+)(,\\s)?"r
warning: there were 1 feature warning(s); re-run with -feature for details
pattern: scala.util.matching.Regex = (\[\w+,\d+\])=(\d+)(,\s)?

scala> val m  = pattern.findAllMatchIn(input).map(m => (m.group(1).trim(), m.group(2).trim())).toMap
m: scala.collection.immutable.Map[String,String] = Map([test,2] -> 11, [test,16] -> 5, [test,11] -> 4, [test,3] -> 12, [test,7] -> 11)

scala> m foreach println
([test,2],11)
([test,16],5)
([test,11],4)
([test,3],12)
([test,7],11)

能否指定输出类型
Map
?第一组和第二组的期望值是多少?嗨,谢尔盖,下面尼亚夫罗的答案正是我想要的。谢谢