我有这样一段文字:
text {text10}
text {text1, text9}
anotherText [
{text2, text5}
{text3, text6}
{test4, text8}
]
这个正则表达式匹配我想要的一切:
val regex = """(.*?) (\[.*?\]|\{(.*?)\})""".r
但是我有一个小问题。我不想匹配大括号本身。所以,我得到的输出是
val line = regex findAllIn configByLines
line.matchData foreach {
m => println("output: "+m.group(2))
}
#output: {text10}
#output: {text1, text9}
#output: [{text2, text5} {text3, text6} {test4, text8}]
但是我想得到 group(2) 的输出为
#output: text10
#output: text1, text9
#output: {text2, text5} {text3, text6} {text4, text8}
如何修复我的正则表达式。
最佳答案
这是非常可行的,尽管您可能想确保您确实需要使用正则表达式来完成它,因为结果不是很漂亮,而且几乎无法维护:
val regex = """[^\{\[]*[\{\[](((?<=\{)[^}]*)|((?<=\[)[^\]]*))[\}\]]""".r
主要技巧是使用零宽度负向后视(例如 (?<=\{)
,以避免匹配“{”本身)。
第 1 组中的匹配文本。
强制 REPL session :
scala> val configByLines = """text {text10}
| text {text1, text9}
| anotherText [
| {text2, text5}
| {text3, text6}
| {test4, text8}
| ]"""
configByLines: String =
text {text10}
text {text1, text9}
anotherText [
{text2, text5}
{text3, text6}
{test4, text8}
]
scala> val regex = """[^\{\[]*[\{\[](((?<=\{)[^}]*)|((?<=\[)[^\]]*))[\}\]]""".r
regex: scala.util.matching.Regex = [^\{\[]*[\{\[](((?<=\{)[^}]*)|((?<=\[)[^\]]*))[\}\]]
scala> val line = regex findAllIn configByLines.replace("\n", " ")
line: scala.util.matching.Regex.MatchIterator = non-empty iterator
scala> line.matchData foreach {
| m => println("output: "+m.group(1))
| }
output: text10
output: text1, text9
output: {text2, text5} {text3, text6} {test4, text8}
关于regex - Scala 正则表达式 - 如何匹配大括号内部但转义大括号本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27599956/