匹配正则表达式后的单词。

huangapple go评论51阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年4月13日 23:54:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76007470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定