【问题标题】:How to match this string patteren?如何匹配这个字符串模式?
【发布时间】:2018-02-26 13:25:48
【问题描述】:

下面是我的字符串。

{" 3/4", "ERW", "A53-A", "STEEL", "PIPE", "STD", "BLK", "PE"} 

我需要用正则表达式匹配这个字符串,请帮我实现这个。

我尝试使用下面的代码 sn-p 来实现这一点,但它部分匹配(我只能匹配 6 个字符串)。

String pattern = "\\s*,\\s*";
String[] sourceValues= listTwo.get(1).toString().split(pattern);

我无法使用此模式匹配第一个和最后一个字符串。

请帮我实现这一点,我需要匹配所有 8 个字符串。

谢谢, 桑德什P

【问题讨论】:

  • 提一下,你期望的输出是什么
  • 有关预期输出的详细信息,请参阅以下链接stackoverflow.com/questions/48882295/…
  • String input = "{\" 3/4\", \"ERW\", \"A53-A\", \"STEEL\", \"PIPE\", \"STD\", \"BLK\", \"PE\"}"; String pattern = "\\s*,\\s*"; String[] sourceValues = input.split(pattern); System.out.println(Arrays.asList(sourceValues)); 输出:[{" 3/4", "ERW", "A53-A", "STEEL", "PIPE", "STD", "BLK", "PE"}]。据我所知,所有字符串都匹配

标签: java regex


【解决方案1】:

你可以试试:

" ?([^"]+)"

这将捕获第 1 组中双引号(没有前导单个空格)之间的内容。现在您有 8 个字符串而不是 6 个。

List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("\" ?([^\"]+)\"").matcher("{\" 3/4\", \"ERW\", \"A53-A\", \"STEEL\", \"PIPE\", \"STD\", \"BLK\", \"PE\"}");
while (m.find()) {
    allMatches.add(m.group(1));
}

Java output test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2011-09-08
    • 2018-10-04
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多