簡體   English   中英

如何在scala正則表達式中匹配括號的內容

[英]How do I match the contents of parenthesis in a scala regular expression

我正在嘗試使用scala正則表達式獲取像這樣的字符串(2.2,3.4)的內容,以獲得像下面的2.2,3.4這樣的字符串

這將使我得到帶有括號的字符串以及所有其他文本的行:

"""\(.*?\)"""

但是我似乎找不到找到僅獲取括號內容的方法。

我試過了: """\\((.*?)\\)""" """((.*?))"""和其他一些組合,沒有運氣。

我過去曾在其他Java應用程序中使用過此代碼: \\\\((.*?)\\\\) ,這就是為什么我認為第一次嘗試在"""\\((.*?)\\)"""上方的行中"""\\((.*?)\\)"""會起作用。

就我而言,這看起來像:

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;

使用先行和后備

您可以使用此正則表達式:

(?<=\()\d+\.\d+,\d+\.\d+(?=\))

或者,如果您不需要括號內的精度:

(?<=\()[^)]+(?=\))

參見演示1演示2

說明

  • 后面的(?<=\\()斷言前面是(
  • \\d+\\.\\d+,\\d+\\.\\d+匹配字符串
  • 或者,在選項2中, [^)]+匹配不包含右括號的任何字符
  • 先行(?=\\))聲稱,接下來就是)

參考

可以試試看

val parenth_contents = "\\(([^)]+)\\)".r
parenth_contents: scala.util.matching.Regex = \(([^)]+)\)

val parenth_contents(r) = "(123, abc)"
r: String = 123, abc

一個偶數樣本正則表達式,用於匹配括號本身和括號內內容的所有匹配項。

(\\([^)]+\\)+)

1st Capturing Group (\([^)]+\)+)
\( matches the character ( literally (case sensitive)
Match a single character not present in the list below [^)]+
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
) matches the character ) literally (case sensitive)
\)+ matches the character ) literally (case sensitive)
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

https://regex101.com/r/MMNRRo/1

\\((.*?)\\)可以工作-您只需要提取匹配的組即可。 要做到這一點最簡單的方法是使用unapplySeq的方法scala.util.matching.Regex

scala> val wrapped = raw"\((.*?)\)".r
wrapped: scala.util.matching.Regex = \((.*?)\)

val wrapped(r) = "(123,abc)"
r: String = 123,abc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM