简体   繁体   English

如何使用Groovy检索某些文件元素并将元素存储为arraylist

[英]How to retrieve certain file elements using groovy and store elements as arraylist

I'm new to groovy programming and I am trying to use groovy to retrieve phone numbers that are randomly present in a text file and then store these values in an arraylist in my groovy program. 我是groovy编程的新手,我试图使用groovy检索随机存在于文本文件中的电话号码,然后将这些值存储在groovy程序的arraylist中。 An example of what the text file looks like is this: 文本文件的示例如下:

Line of code Hello how are you 111-111-1111 Cat dog dog cat 999-999-9999 Another line of code 777-777-7777 代码行您好,您好吗111-111-1111 Cat dog dog cat 999-999-9999另一行代码777-777-7777

The output I'm trying to display: 111-111-1111 999-999-9999 777-777-7777 我尝试显示的输出:111-111-1111 999-999-9999 777-777-7777

I know how to reference the file and retrieve all lines of code and specific numbers/words/etc., but I am unsure of the groovy way to retrieve just the phone numbers present in the text file 我知道如何引用文件并检索所有代码行以及特定的数字/单词/等,但是我不确定仅检索文本文件中存在的电话号码的常规方法

The easiest way to add an element to a list is += operator. 将元素添加到列表的最简单方法是+=运算符。

Below you have an example program, which extracts phone numbers from each source row of a multiline string, collects them in a list, and prints the list. 下面有一个示例程序,该程序从多行字符串的每个源行中提取电话号码,将其收集在列表中,然后打印该列表。

def src = '''\
Line of code Hello how are you 111-111-1111 Cat dog dog cat 999-999-9999.
I'm fine and how are you 111-111-2222 Cat dog dog cat 999-999-8888.
No phone number here.
Another line of code  777-777-8888\
'''
def pat = ~/\b\d{3}-\d{3}-\d{4}\b/
def phones = []
def cnt = 0
src.eachLine{
  def matcher = (it =~ pat)
  def mCnt = matcher.getCount()
  printf("Row %d: %s / %d phones.\n", ++cnt, it, mCnt)
  for (i = 0; i < mCnt; ++i) {
    phones += matcher[i]
  }
}
printf("%d phones: %s.\n", phones.size(), phones.join(', '))

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

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