[Regular expression] answers questions about regular expression segmentation online.

Source: Internet
Author: User
[Regular expression] asks a regular expression segmentation question. online solution ~ Objective: to use a regular expression to separate keywords. Assume that the keyword is (with multiple spaces in the middle): You & nbsp; I & nbsp; she uses the asterisk: print_r (preg_split (s *), & nbsp; $ _ POST [query]); result: Array & nbsp; (& nbsp; [0] & nbsp; & gt; & [regular expression] ask a question about regular expression Segmentation. online solution ~
Objective: to use a regular expression to separate keywords.

Assume that the keyword is (with multiple spaces in the middle): You and her

Use asterisks:
print_r(preg_split("/(\s*)/", $_POST['query']));

Result: Array ([0] => [1] =>? [2] =>? [3] =>? [4] => [5] =>? [6] =>? [7] =>? [8] => [9] =>? [10] =>? [11] =>? [12] =>)

Use the plus sign: print_r (preg_split ("/(\ s +)/", $ _ POST ['query']);
Result: Array ([0] => you [1] => I [2] => She)

Why?

Regular expression manual:
* Matches the previous subexpression zero or multiple times. For example, zo * can match "z" and "zoo ". * Is equivalent to {0 ,}.
+ Match the previous subexpression once or multiple times. For example, 'Zo + 'can match "zo" and "zoo", but cannot match "z ". + Is equivalent to {1 ,}.

Is one matching zero or multiple times, and one matching once or multiple times, that the difference is so big? Why can't I understand why asterisks cause garbled characters ~~~



------ Solution --------------------
* It can be 0 times. do you need to distinguish by space? There are also numbers of spaces ~
------ Solution --------------------
It should have matched 0 times.
------ Solution --------------------
\ S * May match 0 characters between the first and second bytes of your encoding, so garbled characters are generated.
------ Solution --------------------
Why use split? is it difficult to directly match a non-empty string?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.