您好我正在开展一个RoR项目。我的参数中有一个字符串。基于预定义的单词,我必须找到两行字符串。
字符串: -
"\"FileParseExitCode\":1,\n\"ParsedText\":SUPA IGA WATERFORD \nCnr Manning g Kent St \nKarawara WA 6152 \nPin: 08 9200 4211 Fax: oe 9200 4212 \nlax Invoice \n138 932 466 \n12/04/2018 PM \nScot User 12 \nAUSSIE NAT SPROG WATER 1.5L $0.99 \nTOTAL \nMaster \nYou saved: $0.08 "
这里我有一个单词“6152”基于这个单词我需要找到这一行的段落:
\nKarawara WA 6152
在“\ nKarawara WA 6152”之前的段落: -
\nCnr Manning g Kent St
所以基本上我想要两条带有预定义词的行。我的话是“6152”我想得到段落: -
\nCnr Manning g Kent St \nKarawara WA 6152
请帮助我实现这一目标。提前谢谢。
答案 0 :(得分:1)
如果str
是您的字符串,则可以使用正则表达式来提取两个连续的行。
target = "6152"
r = /
\n # match end of line
[^\n]* # match zero or more chars other than \n
\n # match end of line
[^\n]* # match zero or more chars other than \n
(?<!\d) # do not match a digit (negative lookbehind)
#{target} # match the target string
(?!\d) # do not match a digit (negative lookahead)
[^\n]* # match zero or more chars other than \n
/x # free-spacing regex definition mode
# => /
\n # match end of line
[^\n]* # match zero or more chars other than \n
\n # match end of line
[^\n]* # match zero or more chars other than \n
(?<!\d) # do not match a digit (negative lookbehind)
6152 # match the target string
(?!\d) # do not match a digit (negative lookahead)
[^\n]* # match zero or more chars other than \n
/x
str[r]
#=> "\nCnr Manning g Kent St \nKarawara WA 6152 "
如果(?<!\d)
包含(?!\d)
,但前面或后面跟着一个或多个数字,则负面后顾(target
)和否定前瞻("6152"
)会阻止匹配。