Regex to find two words on the page

后端 未结 5 1816
無奈伤痛
無奈伤痛 2021-01-30 11:04

I\'m trying to find all pages which contain words \"text1\" and \"text2\". My regex:

text1(.|\\n)*text2 

it doesn\'t work..

相关标签:
5条回答
  • 2021-01-30 11:26
    text0[\s\S]*text1
    

    Try this.This should do it for you.

    What this does is match all including multiline .similar to having .*? with s flag.

    \s takes care of spaces,newlines,tabs \S takes care any non space character.

    0 讨论(0)
  • 2021-01-30 11:31

    Adding a response for IntelliJ

    Building on @OnlineCop's answer, to swap the order of two expressions in IntelliJ,you would style the search as in the accepted response, but since IntelliJ doesn't allow a one-line version, you have to put the replace statement in a separate field. Also, IntelliJ uses $ to identify expressions instead of \.

    For example, I tend to put my nulls at the end of my comparisons, but some people prefer it otherwise. So, to keep things consistent at work, I used this regex pattern to swap the order of my comparisons:

    Notice that IntelliJ shows in a tooltip what the result of the replacement will be.

    0 讨论(0)
  • 2021-01-30 11:39

    If you want the regex to match over several lines I would try:

    text1[\w\W]*text2
    

    Using . is not a good choice, because it usually doesn't match over multiple lines. Also, for matching single characters I think using square brackets is more idiomatic than using ( ... | ... )

    If you want the match to be order-independent then use this:

    (?:text1[\w\W]*text2)|(?:text2[\w\W]*text1)
    
    0 讨论(0)
  • 2021-01-30 11:42

    If your IDE supports the s (single-line) flag (so the . character can match newlines), you can search for your items with:

    (text1).*(text2)|\2.*\1
    

    Example with s flag

    If the IDE does not support the s flag, you will need to use [\s\S] in place of .:

    (text1)[\s\S]*(text2)|\2[\s\S]*\1
    

    Example with [\s\S]

    Some languages use $1 and $2 in place of \1 and \2, so you may need to change that.

    EDIT:

    Alternately, if you want to simply match that a file contains both strings (but not actually select anything), you can utilize look-aheads:

    (?s)^(?=.*?text1)(?=.*?text2)
    

    This doesn't care about the order (or number) of the arguments, and for each additional text that you want to search for, you simply append another (?=.*?text_here). This approach is nice, since you can even include regex instead of just plain strings.

    0 讨论(0)
  • 2021-01-30 11:49

    For me works text1*{0,}(text2){0,}.

    With {0,} you can decide to get your keyword zero or more times OR you set {1,x} to get your keyword 1 or x-times (how often you want).

    0 讨论(0)
提交回复
热议问题