正则表达式捕获一个字符串

时间:2018-05-16 09:39:39

标签: regex

从我需要捕获的测试字符串中,字符串Ec2 Instances which are ... .micro此字符串在我的测试字符串中重复,稍有变化。

喜欢,停止或跑步 实例ID可能会更改

我试过

^Ec2 Instances.*micro$

但它不适合我。

测试字符串

 'ingestionTime': 1526375668364, 'eventId': '34039314519276244324908423608603573165487083445254619137'}, {'logStreamName': '2018/05/15/[$LATEST]8b2aa0fa731f4534afc62a106ab3aead', 'timestamp': 1526375653280, 'message':"Ec2 Instances which are running:  Instance ID:  i-006690f105487930f Instance state:  {'Code': 16, 'Name': 'running'} Instance type:  t2.micro", 'ingestionTime': 1526375668364, 'eventId': '34039314521038003195592342836784894909026304004227072002'}, {'logStreamName': '2018/05/15/[$LATEST]8b2aa0fa731f4534afc62a106ab3aead', 'timestamp': 1526375653280, 'message': 'END RequestId: 553e166e-5820-11e8-9bd1-0d6fafd1c3b2', 'ingestionTime': 1526375668364, 'eventId': '34039314521038003195592342836784894909026304004227072003'}, {'logStreamName': '2018/05/15/[$LATEST]8b2aa0fa731f4534afc62a106ab3aead', 'timestamp': 1526375653280, 'message': 'REPORT RequestId: 553e166e-5820-11e8-9bd1-0d6fafd1c3b2\tDuration: 487.80 ms\tBilled Duration: 500 ms \tMemory Size: 128 MB\tMax Memory Used: 39 MB\t', 'ingestionTime': 1526375668364, 'eventId': '34039314521038003195592342836784894909026304004227072004'}, {'logStreamName': '2018/05/15/[$LATEST]e9c838560b4a43a8beab55c09b8cff61', 'timestamp': 1526389097179, 'message': 'START RequestId: a27ee858-583f-11e8-942c-83f12a7709a7 Version: $LATEST', 'ingestionTime': 1526389097176, 'eventId': '34039614330004076976238280940123439283024120673455898624'}, {'logStreamName': '2018/05/15/[$LATEST]e9c838560b4a43a8beab55c09b8cff61', 'timestamp': 1526389097665, 'message': 
       "Ec2 Instances which are stopped:  Instance ID:  i-0ab4e0874254619137 Instance state:  {'Code': 80, 'Name': 'stopped'} Instance type:  t2.micro", 'ingestionTime': 1526389097651, 'eventId': '34039614340842239142724163787484244289861010676797800448'}, {'logStreamName': '2018/05/15/[$LATEST]e9c838560b4a43a8beab55c09b8cff61', 'timestamp': 1526389097864, 'message': 
       "Ec2 Instances which are running:  Instance ID:  i-006690f2546191374r Instance state:  {'Code': 16, 'Name': 'running'} Instance type:  t2.micro", 'ingestionTime': 1526389097851, 'eventId': '34039614345280087437231757792891484413311004850060001280'}, {'logStreamName': '2018/05/15/[$LATEST]e9c838560b4a43a8beab55c09b8cff61', 'timestamp': 1526389097864, 'message': 
       "Ec2 Instances which are running:  Instance ID:  i-0384972254619137r4 Instance state:  {'Code': 16, 'Name': 'running'} Instance type:  t2.micro

1 个答案:

答案 0 :(得分:2)

您的预期匹配似乎在""之间。这意味着,^(字符串的开头)和$(字符串锚的结尾)应该用双引号替换。

所以,您可以考虑使用

/"Ec2 Instances.*?micro"/g

请参阅regex demo

请注意使用与*?Ec2之间的最少量字符匹配的micro量词来查找有效匹配。

另外,我添加了g全局修饰符以在regex测试器中启用多重匹配。无论您使用何种环境,都应参考相关文档,以了解如何匹配字符串中多次出现的模式。