正则表达式。如何从文本中获取字符串?

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

Regular expression. How to get strings from text?

问题

在第一种情况下,这些行位于

> "\n 和 \

在第二种情况下,这些行位于

> message\n 和 \

之间可以有任意数量的行。

如何通过单个查询选择/获取这些字符串?

我希望有人能够编写一个适当的正则表达式。

我可以使用以下正则表达式

("\n|message\n)+(.*\n.*\n)

我想要的文本位于第二组中,但仅限于两行。我不知道如何编写一个适用于任意行数的表达式,以及如何添加一个以

(\\n) 或 (^\\) 结束的条件。
英文:

There is a text:

"
Sample text 1!
,,Sample&.,? text 2?
\


-message
32 Another sample text 3
... sample text 4&
!Sample text 5%
\

https://regex101.com/r/LwySuM/1

In the first case, the lines are between

> "\n and \

In the second, the lines are between

> message\n and \

There can be any number of lines in between.

How can I select/get these strings in a single query?

I hope someone will write a proper regular expression.

I can do this

("\n|message\n)+(.*\n.*\n)

The text I want is in the second group but it's only for two lines. I don't know how to write a expression for any number of lines and how to add a condition that ends with

(\\n) or (^\\)

答案1

得分: 0

> _"... 我想要的文本在第二组,但只有两行。我不知道如何写一个适用于任意行数的表达式 ..."_

你正在寻找 _单行_ 模式,即 `s`。
在这种模式下,`.` 会匹配换行符。

这里的 `\s+?^` 用于跳过换行符,以便它们不在 _捕获组_ 内。

```none
/(?:-message|")\s+?^(.+?)\s+?^\\/gms
英文:

> "... The text I want is in the second group but it's only for two lines. I don't know how to write a expression for any number of lines ..."

You are looking for single-line mode, s.
This is where a . will additionally match new-line delimiters.

The \s+?^ here is used to skip-over the new-line delimiters, so they are not within the capture group.

/(?:-message|")\s+?^(.+?)\s+?^\\/gms

huangapple
  • 本文由 发表于 2023年6月29日 05:00:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576673.html
匿名

发表评论

匿名网友

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

确定