简体   繁体   中英

Regex to match the nearest character backwards

I have this string:

P.1           P.2                    P.3                   P.4  
          ASTON VETERINARY HOSPITAL                                       
            Page 1/2   
        00 PennelJ Road  
      Media, PA 19063-5983 
          (610) 474-5670           
Client :      

I want to get the text in between Client and P.\\d . Here is the demo: Regex

(P.\d)[\s\S]*(?=^.+Client :?)

The problem is that it matches from the first Page P.1 . I need the nearest P.\\d before Client.

How to change the regex so that it would match from P.4 .

I tried this with non-greedy operators but that's not going to work. I'd try to move away from having the entire regex match precisely what you want, and use groups instead. Then you can just write a matcher to match any number of those P.1 constructs, and it makes your scan for the Client string at the end a lot simpler because you don't have to try to do it as a lookahead. Thus:

String x = "P.1  P.2    P.3   P.4 foobar  Client :";
Pattern p = Pattern.compile("((P\\.\\d)(.*(P\\.\\d))*)+(?<result>.*)Client");
Matcher m = p.matcher(x);
System.out.println(m.find());
System.out.println(m.group("result"));

Seems to produce precisely what you want. The syntax (?<whatever>REGEX HERE) is regular-expression-ese for: Let me grab just this bit later by asking for the group 'whatever'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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