[英]Split string based on parantheses
我正在編寫基於冒號 (:) 分割一行的 Scala 代碼。 例如,對於如下所示的輸入:
sparker0i@outlook.com : password
我正在做line.split(" : ")
(本質上是 Java)並在控制台上打印電子郵件和密碼。
現在我的要求已經改變,現在一行看起來像:
(sparker0i@outlook.com,sparker0i) : password
我想分別打印電子郵件、用戶名和密碼。
我首先嘗試拆分括號來嘗試正則表達式,但這不起作用,因為它不正確( val lt = line.split("[\\\\\\\\(||//)]")
)。 請用正確的正則表達式/拆分邏輯指導我。
我不是 Scala 用戶,但我認為您可以使用 Pattern 和 matcher 來提取此信息,而不是 split,您的正則表達式可以使用以下組:
\((.*?),(.*?)\) : (.*)
然后您可以提取第 1 組作為電子郵件,第 2 組作為用戶名,第 3 組作為密碼。
val input = "(sparker0i@outlook.com,sparker0i) : password"
val pattern = """\((.*?),(.*?)\) : (.*)""".r
pattern.findAllIn(string).matchData foreach {
m => println(m.group(1) + " " + m.group(2) + " " + m.group(3))
}
我會使用的正則表達式:
\((.*?),([^)]+)\) : (.+)
\( # Matches (
( # Start of capture group 1
(.*?) # Capture 0 or more characters until ...
) # End of capture group 1
, # matches ,
( # start of capture group 2
[^)]+ # captures one or more characters that are not a )
) # end of capture group 2
\) # Matches )
: # matches ' : '
( # start of capture group 3
(.+) # matches rest of string
) # end of capture group 3
Java 實現將是:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Test
{
public static void main(String[] args) {
String s = "(sparker0i@outlook.com,sparker0i) : password";
Pattern pattern = Pattern.compile("\\((.*?),([^)]+)\\) : (.+)");
Matcher m = pattern.matcher(s);
if (m.matches()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
}
}
}
印刷:
sparker0i@outlook.com
sparker0i
password
在 scala 2.13 中,有一個沒有正則表達式的簡單解決方案:
Welcome to Scala 2.13.1 (OpenJDK 64-Bit Server VM, Java 1.8.0_222).
Type in expressions for evaluation. Or try :help.
scala> val input = "(sparker0i@outlook.com,sparker0i) : password"
input: String = (sparker0i@outlook.com,sparker0i) : password
scala> val s"($mail,$user) : $pwd" = input
mail: String = sparker0i@outlook.com
user: String = sparker0i
pwd: String = password
這是沒有做太多改變
String s = "(sparker0i@outlook.com,sparker0i) : password";
// do whatever you were doing
String[] sArr = s.split(":");
sArr[0] = sArr[0].replaceAll("[(|)]",""); // just replace those parenthesis with empty string
System.out.println(sArr[0] + " " + sArr[1]);
輸出
sparker0i@outlook.com,sparker0i password
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.