a way of writing in which a regular expression matches a character other than a parenthesis containing a specific character string

Asked 1 years ago, Updated 1 years ago, 60 views

If there is a sentence below, please tell me how to write a regular expression that matches anything other than [switch].

Hello. [feedback] Good morning.[switch] Thank you.

Note:
I also want to match the [feedback] of the image.(The method is to match anything other than [switch].

Note: I want to match the [feedback] of the image.(The method is to match anything other than [switch].)

php regular-expression

2022-09-30 19:39

3 Answers

Remove parts that match regular expressions

"Take out anything other than the part that matches the regular expression pattern" can be achieved by "removing the part that matches the regular expression pattern."
Use preg_replace to replace it with an empty character.

<?php
$str='[switch] Hello. [feedback] Good morning.[switch] Thank you.';
$new_str=preg_replace('/\[switch\]/',',',$str);
echo "$new_str\n";

Output:

Hello. [feedback] Good morning.Thank you very much。

Delete the part that matches the string

Metropolis' comment points out that in this example, the string you want to delete is fixed and [switch], so you don't need to use regular expressions.

using str_replace
$new_str=str_replace('[switch]',',',$str);

It is sufficient to do so.


2022-09-30 19:39

If you are going to separate [switch] from the rest, how about the following?
$1 (or \1) and $2 (\2) each contain "Hello [feedback] good morning" and "Thank you very much."

(.*)\[switch\](.*)

I'm sorry if I misunderstood the meaning of the title.


2022-09-30 19:39

For example,

  • head^,\A
  • Butt$,\z
  • [switch]head(?=\[switch\])
  • [switch] bottom (?<=\[switch\])

as
  • From the beginning of the string to the beginning of [switch]^(.*?)(?=\[switch\])
  • [switch] from the bottom to the head of [switch](?<=\[switch\])(.*?)(?=\[switch\])
  • [switch] from the bottom to the bottom of the string (?<=\[switch\])(.*?)$

Why don't you connect with |?

(?:^(.*?)(?=\[switch\]))|(?:(?<=\[switch\])(.*?)(?=\[switch\]))|(?:(?<=\[switch\])(.*?)$)

Depending on the situation, adjust it separately as ^$ is appropriate or \A\z.

Additional information

At the beginning of the string or from the bottom of the [switch] (?:^|(?<=\[switch\]))
(?:(?=\[switch\])|$) up to the end of the string or up to the head of the [switch]
It may be simpler to think that

(?:^|(?<=\[switch\]))(.*?)(?:(?=\[switch\])|$)

For your information.


2022-09-30 19:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.