英文:
Getting a word after a word match in regex
问题
I want to get two specific words using regex after a word.
So I have the following text:
code: 'dev-foo-1', text: foo, bla:, blabla, ..., tokenId: '1234566343434', accountId: '123456789',...
I want from this text only the code dev-foo-1
and the account id 123456789
.
But I am having a problem selecting those two.
I tried to do something like:
code:'\([a-z]{3})([a-z]+)([0-9])'\accountId: \'([0-9])'
which is incorrect.
英文:
I want to get two specific words using regex after a word
So I have the following text
code: 'dev-foo-1', text: foo, bla:, blabla, ..., tokenId: '1234566343434', accountId: '123456789',...
I want from this text only the code dev-foo-1
and the account id 123456789
But I am having problem to select those two.
I tried to do something like
code:'\([a-z]{3})([a-z]+)([0-9])'\accountId: \'([0-9])'
which it's wrong.
答案1
得分: 1
Here is the translated code part:
如果code
总是在accountId
之前出现,那你已经很接近答案了。你需要在code
和代码之间加一个空格,并在代码各部分之间加上破折号:
code: '([a-z]{3}-[a-z]+-[0-9])'
然后在accountId
之前可以有任意字符,所以你需要使用.*
来匹配它们。实际上,你可以使用.*?
来实现非贪婪匹配。
最后,你的accountId
目前只匹配单个数字,但你可能想要匹配一个或多个数字,可以使用[0-9]+
:
code: '([a-z]{3}-[a-z]+-[0-9])'.*?accountId: '([0-9]+)'
... 完成。
英文:
(Note that I've ignored backslashes in your code because they appear to be inconsistently applied – you'll need to add slashes before each single-quote if you're using single-quoted strings to delimit your patterns)
If code
always appears before accountId
then you're pretty close to an answer. You're missing a space between code
and the code, and also the dashes between the sections of the code:
code: '([a-z]{3}-[a-z]+-[0-9])'
There can then be any characters at all before the accountId
, so you'll need .*
to match them. Actually, you can use .*?
to be non-greedy.
Finally, your accountId
currently matches only a single digit, but you'll presumably want to match one or more with [0-9]+
:
code: '([a-z]{3}-[a-z]+-[0-9])'.*?accountId: '([0-9]+)'
... and we are done.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论