【问题标题】:Java how to setup regex for this stringJava如何为这个字符串设置正则表达式
【发布时间】:2012-07-21 20:54:31
【问题描述】:

所以我试图通过匹配器对象从存储在我的在线数据库中的一个字符串中提取两个字符串。

每个字符串都出现在 s:64: 之后并用引号引起来 示例 s:64:"stringhere"

我目前正在尝试获取它们,但我尝试过的任何正则表达式都失败了,

 Pattern p = Pattern.compile("I don't know what to put as the regex");
Matcher m = p.matcher(data);

话虽如此,我所需要的只是将在匹配器中返回两个字符串的正则表达式,因此 m.group(1) 是我的第一个字符串,m.group(2) 是我的第二个字符串。

【问题讨论】:

  • 请学习正则表达式,使用 rubular.com 等在线正则表达式测试器(该站点适用于 Ruby,但 Ruby 中的正则表达式与 Java 的语法有些相似)。
  • @nhahtdh gskinner.com/RegExr 是另一个不错的在线正则表达式测试器。

标签: java regex string pattern-matching matcher


【解决方案1】:

试试这个正则表达式:-

s:64:\"(.*?)\"

代码:

Pattern pattern = Pattern.compile("s:64:\"(.*?)\"");
Matcher matcher = pattern.matcher(YourStringVar);
// Check all occurance
int count = 0;
while (matcher.find() && count++ < 2) {
    System.out.println("Group : " + matcher.group(1));
}

这里group(1)返回每个匹配项。

输出:

Group : First Match
Group : Second Match

参考LIVE DEMO

【讨论】:

    【解决方案2】:
    String data = "s:64:\"first string\" random stuff here s:64:\"second string\"";
    Pattern p = Pattern.compile("s:64:\"([^\"]*)\".*s:64:\"([^\"]*)\"");
    Matcher m = p.matcher(data);
    if (m.find()) {
      System.out.println("First string: '" + m.group(1) + "'");
      System.out.println("Second string: '" + m.group(2) + "'");
    }
    

    打印:

    第一个字符串:'第一个字符串'
    第二个字符串:'第二个字符串'

    【讨论】:

    • 我相信你在s64之间缺少:
    • 谢谢你,工作就像一个魅力。我真的需要学习如何构造正则表达式。
    【解决方案3】:

    你需要的正则表达式应该是compile("s:64:\"(.*?)\".*s:64:\"(.*?)\"")

    【讨论】:

      猜你喜欢
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多