简体   繁体   English

如何使用 RegExp 分隔文本和图像路径?

[英]How to separate text and image path using RegExp?

I have the following strings:我有以下字符串:

this was the url SERVER_UPLOAD_FILE_PATH____::5e2650c2-728c-40af-99a4eb100c432091.png____SERVER_UPLOAD_END click here to view details
SERVER_UPLOAD_FILE_PATH____::68d37b07-d694-47af-a16a-8adbe400ac67.png____SERVER_UPLOAD_END Hector where are you Hello world how are you
SERVER_UPLOAD_FILE_PATH____::ad4d7360-9c6c-44fa-bcbb-0db7e671e036.png____SERVER_UPLOAD_END Execuse Me

How can I separate the text and image path using RegExp ?如何使用RegExp分隔文本和图像路径?

This is the expected result:这是预期的结果:

this was the url 
SERVER_UPLOAD_FILE_PATH____::5e2650c2-728c-40af-99a4eb100c432091.png____SERVER_UPLOAD_END
click here to view details

Use this RegExp to match the text you don't want:使用此RegExp匹配您不想要的文本:

[^ ]{20,}

It matches the unwanted strings because they are the only character sequences that continue on for at least 20 characters without a single space.它匹配不需要的字符串,因为它们是唯一一个持续至少20字符且没有一个空格的字符序列。

[^ ] means no space. [^ ]表示没有空格。 {20,} means repeated at least 20 times. {20,}表示至少重复20次。

Then .split() the entire string using the unwanted text as a delimiter.然后.split()使用不需要的文本作为分隔符的整个字符串。

 [ 'this was the url SERVER_UPLOAD_FILE_PATH____::5e2650c2-728c-40af-99a4eb100c432091.png____SERVER_UPLOAD_END click here to view details', 'SERVER_UPLOAD_FILE_PATH____::68d37b07-d694-47af-a16a-8adbe400ac67.png____SERVER_UPLOAD_END Hector where are you Hello world how are you', 'SERVER_UPLOAD_FILE_PATH____::ad4d7360-9c6c-44fa-bcbb-0db7e671e036.png____SERVER_UPLOAD_END Execuse Me' ].map(s => s.split(s.match(/[^ ]{20,}/))).flat().map(s => s.trim()).filter(Boolean).forEach(s => console.log(s));

You can also separate the image path and the text using this regular expression:您还可以使用以下正则表达式分隔图像路径和文本:

/(.*?)(SERVER_UPLOAD_FILE_PATH.+?SERVER_UPLOAD_END)(.+)/

This will always return you three groups where the first can be empty.这将始终返回三个组,其中第一个可以为空。

Here is an example of how you can use the regular expression:以下是如何使用正则表达式的示例:

 const a = ['this was the url SERVER_UPLOAD_FILE_PATH____::5e2650c2-728c-40af-99a4eb100c432091.png____SERVER_UPLOAD_END click here to view details', 'SERVER_UPLOAD_FILE_PATH____::68d37b07-d694-47af-a16a-8adbe400ac67.png____SERVER_UPLOAD_END Hector where are you Hello world how are you', 'SERVER_UPLOAD_FILE_PATH____::ad4d7360-9c6c-44fa-bcbb-0db7e671e036.png____SERVER_UPLOAD_END Execuse Me']; const regex = /(.*?)(SERVER_UPLOAD_FILE_PATH.+?SERVER_UPLOAD_END)(.+)/; a.forEach(s => { const match = s.match(regex); match.forEach((m, i) => console.log(i, m.trim())); console.log() });

The group at index 0 is always the original string.索引 0 处的组始终是原始字符串。 The interesting groups start from index 1.有趣的组从索引 1 开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM