根据括号拆分字符串

时间:2020-03-23 11:38:23

标签: java regex scala split

我正在编写Scala代码,该代码根据冒号(:)分割一行。 例如,对于如下所示的输入:

sparker0i@outlook.com : password

我正在做line.split(" : ")(本质上是Java)并在控制台上打印电子邮件和密码。

现在我的要求已更改,现在一行如下:

(sparker0i@outlook.com,sparker0i) : password

我想分别打印电子邮件用户名密码

我已经尝试过首先分割正则表达式来尝试正则表达式,但这没有用,因为它是不正确的(val lt = line.split("[\\\\(||//)]"))。请为我提供正确的正则表达式/拆分逻辑。

4 个答案:

答案 0 :(得分:4)

我不是scala用户,但我认为您可以使用Pattern和Matcher提取此信息,而不必拆分,您的正则表达式可以使用类似以下的组:

\((.*?),(.*?)\) : (.*)

regex demo

然后您可以提取第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))
}

此帖子的积分https://stackoverflow.com/a/3051206/5558072

答案 1 :(得分:1)

我将使用的正则表达式:

\((.*?),([^)]+)\) : (.+)

Regex Demo

\(        # 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

Java Demo

答案 2 :(得分:1)

在scala 2.13中,有一个简单的解决方案,无需regrex:

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

答案 3 :(得分:0)

这没有做太多改变

    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