如何使用正则表达式忽略文本中的空格和回车符

发布于 2024-09-16 07:10:58 字数 459 浏览 2 评论 0原文

我对 stackoverflow 很陌生,所以我不知道以前是否有人问过这个问题,但我似乎找不到任何过去的问题暗示答案。非常感谢任何帮助,并提前致谢。

我有这样的文本:

{
   1282837200, -- [1]
   "Type", -- [2]
   "Name", -- [3]
   "Reason", -- [4]
   Amount, -- [5]
  }, -- [1]
  {
   1282838220, -- [1]
   "Type", -- [2]
   "Name", -- [3]
   "Reason", -- [4]
   Amount, -- [5]
  }, -- [2]

我需要为其创建正则表达式并提取必要的数据。我了解如何使用 PHP 中的正则表达式、使用没有“空格”或回车符的源文本从源文件中提取数据。

但我需要帮助创建一个包含该源代码中包含的空格等的表达式。

Im quite new to stackoverflow so I dont know if this question has been asked before, but I cant seem to find any past questions which hint at the answer. Any help is really appreciated and thanks in advance.

I have this text:

{
   1282837200, -- [1]
   "Type", -- [2]
   "Name", -- [3]
   "Reason", -- [4]
   Amount, -- [5]
  }, -- [1]
  {
   1282838220, -- [1]
   "Type", -- [2]
   "Name", -- [3]
   "Reason", -- [4]
   Amount, -- [5]
  }, -- [2]

Which I need to create a regular expression for and extract the necessary data. I understand how to extract data from source files using regular expressions within PHP, using source text which has no "whitespace" or carriage returns.

But I need help with creating an expression which includes the whitespace etc. included within this source.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝梦月影 2024-09-23 07:10:58

\s 是空白符号,可能包含换行符,也可能不包含换行符,无论如何都有 [\r\n] ,忽略这些就可以了。您还可以告诉您到底想做什么,甚至发布您到目前为止拥有的正则表达式,以便如果您愿意,我可以进一步帮助您。

编辑:我只是猜测,您想要的正则表达式可能是这样的:

/\s*{[\s\n\r]*^\s*(\d+).*[\s\n\r]*^\s*"([^"]+)".*[\s\n\r]*^\s*"([^"]+)".*[\s\n\r]*^\s*"([^"]+)".*[\s\n\r]*^\s*(\w+).*[\s\n\r]*^\s*},.*[\s\n\r]*^/m

这匹配一个块并忽略括号中的数字。 /m 开关触发多行模式。

\s is the symbol for whitespace, which may or may not include newlines, anyway there's [\r\n] for them, ignore these and that's it. You could also tell what exactly you want to do or even post the regex you have so far so I can help you further if you want.

EDIT: I'm just guessing, the regexp you want may be this:

/\s*{[\s\n\r]*^\s*(\d+).*[\s\n\r]*^\s*"([^"]+)".*[\s\n\r]*^\s*"([^"]+)".*[\s\n\r]*^\s*"([^"]+)".*[\s\n\r]*^\s*(\w+).*[\s\n\r]*^\s*},.*[\s\n\r]*^/m

This matches one block and disregards the numbers in brackers. /m switch triggers multiline mode.

左岸枫 2024-09-23 07:10:58

如果您只是尝试删除所有空格,请尝试以下操作:
$string = preg_replace('/\s+/s', '', $string);

\s+ 匹配一个或多个空格、制表符和换行符。 /s 中的 s 告诉正则表达式将字符串视为一个整体,而不是一次一行。

If you're trying to simply remove all whitespace, try the following:
$string = preg_replace('/\s+/s', '', $string);.

\s+ matches one or more spaces, tabs, and newlines. The s in /s tells the regex to look at the string as a whole as opposed to one line at a time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文