问题描述
我正在尝试使用 Scala 正则表达式获取像这样 (2.2,3.4)
这样的字符串的内容,以获得像下面这样的字符串 2.2,3.4
I'm trying to get at the contents of a string like this (2.2,3.4)
with a scala regular expression to obtain a string like the following 2.2,3.4
这将使我得到带有括号的字符串以及来自一行其他文本的所有内容:
This will get me the string with parenthesis and all from a line of other text:
"""\(.*?\)"""
但我似乎无法找到只获取括号内容的方法.
But I can't seem to find a way to get just the contents of the parenthesis.
我试过: """\((.*?)\)""" """((.*?))"""
和其他一些组合,但没有运气.
I've tried: """\((.*?)\)""" """((.*?))"""
and some other combinations, without luck.
我过去在其他 Java 应用程序中使用过这个:\\((.*?)\\)
,这就是为什么我认为 """\((.*?)\)"""
会起作用.
I've used this one in the past in other Java apps: \\((.*?)\\)
, which is why I thought the first attempt in the line above """\((.*?)\)"""
would work.
就我而言,这看起来像:
For my purposes, this looks something like:
var points = "pointA: (2.12, -3.48), pointB: (2.12, -3.48)"
var parenth_contents = """\((.*?)\)""".r;
val center = parenth_contents.findAllIn(points(0));
var cxy = center.next();
val cx = cxy.split(",")(0).toDouble;
推荐答案
使用 Lookahead 和 Lookbehind
您可以使用此正则表达式:
You can use this regex:
(?<=\()\d+\.\d+,\d+\.\d+(?=\))
或者,如果您不需要括号内的精度:
Or, if you don't need precision inside the parentheses:
(?<=\()[^)]+(?=\))
说明
- 后视
(?<=\()
断言(
\d+\.\d+,\d+\.\d+
匹配字符串- 或者,在选项 2 中,
[^)]+
匹配任何不是右括号的字符 - 前瞻
(?=\))
断言接下来是)
- The lookbehind
(?<=\()
asserts that what precedes is a(
\d+\.\d+,\d+\.\d+
matches the string- or, in Option 2,
[^)]+
matches any chars that are not a closing parenthesis - The lookahead
(?=\))
asserts that what follows is a)
参考
这篇关于如何匹配scala正则表达式中括号的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!