使用regex从“variable = value”字符串中提取值

时间:2022-10-25 08:05:15

I have a string as shown below

我有一个字符串,如下所示

String1 = aaaa
String2 = bbbb
String4 = cccc
String5 = " 
     abcd;
     bcda
     cdas"
String6 = dddd

I need to extract the string after "=".
In String 5, I need to extract the string in between double quotes " ".
I am able to achieve this using substring and indexof. How can I achieve this in Perl regex?

我需要在“=”之后提取字符串。在字符串5中,我需要在双引号“”之间提取字符串。我能够使用substring和indexof实现这一点。我怎样才能在Perl正则表达式中实现这一目标?

1 个解决方案

#1


1  

RegEx: /^[a-zA-Z0-9]+\s*=\s*([^"']+?$|"[^"]+|'[^']+)/gm

This also takes care of both cases with single and double quotes and also simple values.

这也用单引号和双引号以及简单值来处理这两种情况。

Text to be matched:

要匹配的文字:

String1 = aaaa  
String2 = bbbb  
String4 = cccc  
String5 = "   
     abcd;  
     bcda  
     cdas"  
String6 = dddd  
String7 = '   
     abcd;  
     bcda  
     cdas'  

Matches:

MATCH 1 `aaaa`
MATCH 2 `bbbb`
MATCH 3 `cccc`
MATCH 4 `" ↵     abcd;↵     bcda↵     cdas`
MATCH 5 `dddd`
MATCH 6 `' ↵     abcd;↵     bcda↵     cdas`

Demo link: http://regex101.com/r/dL4cS3

演示链接:http://regex101.com/r/dL4cS3

#1


1  

RegEx: /^[a-zA-Z0-9]+\s*=\s*([^"']+?$|"[^"]+|'[^']+)/gm

This also takes care of both cases with single and double quotes and also simple values.

这也用单引号和双引号以及简单值来处理这两种情况。

Text to be matched:

要匹配的文字:

String1 = aaaa  
String2 = bbbb  
String4 = cccc  
String5 = "   
     abcd;  
     bcda  
     cdas"  
String6 = dddd  
String7 = '   
     abcd;  
     bcda  
     cdas'  

Matches:

MATCH 1 `aaaa`
MATCH 2 `bbbb`
MATCH 3 `cccc`
MATCH 4 `" ↵     abcd;↵     bcda↵     cdas`
MATCH 5 `dddd`
MATCH 6 `' ↵     abcd;↵     bcda↵     cdas`

Demo link: http://regex101.com/r/dL4cS3

演示链接:http://regex101.com/r/dL4cS3