正则表达式只在两个字符之间获取文本

时间:2021-02-11 21:46:51

This is probably not that easy as you think :)

这可能不像你想象的那么容易:)

I want to match something exactly between a character and 2 characters, and only between these two. The first character is ! and the second is ']

我想在字符和2个字符之间精确匹配,并且只在这两个字符之间匹配。第一个角色是!第二个是']

Example string: Hello 123 !get this text'] hello 1234

示例字符串:Hello 123!获取此文本'] hello 1234

So I want to capture only "get this text",

所以我想只捕获“获取此文本”,

E.g. this should also only catch "get this text" :

例如。这也应该只捕获“获取此文本”:

Hello 123 ! hello !get this text'] hello 1234

and not the "hello !get this text"

而不是“你好!得到这个文本”

This regex seems to only work on the first example: (?<=!)[^}]*(?='])

这个正则表达式似乎只适用于第一个例子:(?<=!)[^}] *(?='])

Thanks

2 个解决方案

#1


1  

Try the following expression:

请尝试以下表达式:

(?<=!)[^!]+?(?='\])
  • (?<=!): Look behind for an exclamation mark !.
  • (?<=!):留意感叹号!

  • [^!]+?: Match one or more characters which are not exclamation marks, and do this lazily one character at a time, checking the following expression after each character matched to know when to stop.
  • [^!] + ?:匹配一个或多个不是感叹号的字符,并且一次懒惰地执行一个字符,在每个字符匹配后检查以下表达式以知道何时停止。

  • (?='\]): Look ahead to see if there is a literal ' which is followed by a literal ].
  • (?='\]):向前看是否有文字'后面跟着文字]。

Here is Regex101 Demo in PHP but it makes no difference in this case.

这是使用PHP的Regex101演示,但在这种情况下没有任何区别。

#2


0  

You can also use simpler regexes with -split and -replace:

您还可以使用-split和-replace更简单的正则表达式:

$t1 = "Hello 123 !get this text'] hello 1234"
$t2 = "Hello 123 ! hello !get this text'] hello 1234"

($t1,$t2) -split '!' -match "']" -replace "'].+",''

get this text
get this text

#1


1  

Try the following expression:

请尝试以下表达式:

(?<=!)[^!]+?(?='\])
  • (?<=!): Look behind for an exclamation mark !.
  • (?<=!):留意感叹号!

  • [^!]+?: Match one or more characters which are not exclamation marks, and do this lazily one character at a time, checking the following expression after each character matched to know when to stop.
  • [^!] + ?:匹配一个或多个不是感叹号的字符,并且一次懒惰地执行一个字符,在每个字符匹配后检查以下表达式以知道何时停止。

  • (?='\]): Look ahead to see if there is a literal ' which is followed by a literal ].
  • (?='\]):向前看是否有文字'后面跟着文字]。

Here is Regex101 Demo in PHP but it makes no difference in this case.

这是使用PHP的Regex101演示,但在这种情况下没有任何区别。

#2


0  

You can also use simpler regexes with -split and -replace:

您还可以使用-split和-replace更简单的正则表达式:

$t1 = "Hello 123 !get this text'] hello 1234"
$t2 = "Hello 123 ! hello !get this text'] hello 1234"

($t1,$t2) -split '!' -match "']" -replace "'].+",''

get this text
get this text