简体   繁体   English

正确的正则表达式

[英]Correct Regular Expression

I'm using Java Regex to read String of the type 我正在使用Java Regex读取类型的String

"{\n  'Step 1.supply.vendor1.quantity':\"80"\,\n
      'Step 2.supply.vendor2.quantity':\"120"\,\n
      'Step 3.supply.vendor3.quantity':\"480"\,\n
      'Step 4.supply.vendor4.quantity':\"60"\,\n}"

I have to detect strings of type 我必须检测类型的字符串

'Step 2.supply.vendor2.quantity':\"120"\,\n.

I'm trying to use pattern and matcher of regex but I'm not able to figure out the correct regular expression for lines like 我正在尝试使用正则表达式的模式和匹配器,但无法为像这样的行找出正确的正则表达式

 <Beginning of Line><whitespace><whitespace><'Step><whitespace><Number><.><Any number & any type of characters><,\n><EOL>.

The <Beginning of Line> and <EOL> I have used for clarification purpose. 为了说明起见,我使用了<Beginning of Line><EOL>

I have tried several patterns 我尝试了几种模式

String regex = "(\\n\\s{2})'Step\\s\\d.*,\n";
String regex = "\\s\\s'Step\\s\\d.*,\n";

I always get IllegalStateException : No match found . 我总是得到IllegalStateException找不到匹配项

I'm not able to find proper material to read on Java Regex with good examples. 我找不到很好的例子来在Java Regex上阅读合适的材料。 Any help would be really great. 任何帮助都将非常棒。 Thanks. 谢谢。

As the others said in the comments, you should really use a JSON Parser. 正如其他人在评论中所说,您应该真正使用JSON解析器。

But if you want to see how it could work with a regex, here is how you can do it : 但是,如果您想了解它如何与正则表达式一起工作,请按以下步骤操作:

  • Take an example of a line you want to capture : Step 1.supply.vendor1.quantity':"80" 以您要捕获的一行为例: Step 1.supply.vendor1.quantity':"80"
  • Replace digits with \\\\d* ( \\\\d matches any digit) \\\\d*替换数字( \\\\d匹配任何数字)
  • Replace dots with \\\\. \\\\.替换点\\\\. (dots need to be escaped) (点必须逃脱)
  • Add some parenthesis around the parts that you want to capture 在要捕获的部分周围添加一些括号

Here is the resulting regex : "Step (\\\\d*)\\\\.supply\\\\.vendor(\\\\d*)\\\\.quantity':\\"(\\\\d*)\\"" 这是生成的正则表达式: "Step (\\\\d*)\\\\.supply\\\\.vendor(\\\\d*)\\\\.quantity':\\"(\\\\d*)\\""

Now, use a Regex and a Matcher : 现在,使用正则RegexMatcher

String input = "{\n  'Step 1.supply.vendor1.quantity':\"80\"\\,\n";
Pattern pattern = Pattern.compile("Step (\\d*)\\.supply\\.vendor(\\d*)\\.quantity':\"(\\d*)\"");
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
  System.out.println(matcher.group(1));
  System.out.println(matcher.group(2));
  System.out.println(matcher.group(3));
}

Output : 输出:

1 //(corresponds to "Step (\\d*)")
1 //(corresponds to "vendor(\\d*)")
80 //(corresponds to "quantity':\"(\\d*)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM