如何在java中提取与regex匹配的模式

时间:2022-09-22 23:52:26

I am working with regex in java. I have a file which contains the following pattern followed and preceded by other text. The pattern:

我在java中使用正则表达式。我有一个文件,其中包含以下模式,后面跟着其他文本。模式:

    Bombay Garden 5995 Mowry Ave Newark, CA (510) 744-6945   
    Bombay Garden 172 E. 3rd Ave. San Mateo, CA (650) 548-9966   
    Bombay Garden 3701 El Camino Real Santa Clara, CA (408) 241-5150   

I have the following regex that matches each line. The regex:

我有以下正则表达式匹配每一行。正则表达式:

(.*?)(\d{1,4})(\s*\w*)*(\w+),(\s*)(CA|AZ|NY)(\s*)(\(?[1-9]\d{2}\)?\s*\d{3}-?\d{4})

This matches one line, but i want to extract the street name, state and the phone number for each of the three branches using Java.

这匹配一行,但我想使用Java提取三个分支中每个分支的街道名称,状态和电话号码。

Can anyone help me with this?

谁能帮我这个?

1 个解决方案

#1


1  

You extract the contents of a capturing group by using group() of the Matcher object, and passing it a group number, ie:

您可以使用Matcher对象的group()提取捕获组的内容,并将其传递给组编号,即:

  Matcher m = Pattern.compile(yourRegex).matcher(yourString)
  while (m.find()) 
  {
      System.out.println(m.group(1));
      System.out.println(m.group(2));
      String state = m.group(6);
      ...
  }

Group 0 is the entire pattern. Group 1 is your first capturing group, ie in your case m.group(6) will return the state.

组0是整个模式。第1组是你的第一个捕获组,即在你的情况下,m.group(6)将返回状态。

#1


1  

You extract the contents of a capturing group by using group() of the Matcher object, and passing it a group number, ie:

您可以使用Matcher对象的group()提取捕获组的内容,并将其传递给组编号,即:

  Matcher m = Pattern.compile(yourRegex).matcher(yourString)
  while (m.find()) 
  {
      System.out.println(m.group(1));
      System.out.println(m.group(2));
      String state = m.group(6);
      ...
  }

Group 0 is the entire pattern. Group 1 is your first capturing group, ie in your case m.group(6) will return the state.

组0是整个模式。第1组是你的第一个捕获组,即在你的情况下,m.group(6)将返回状态。