I am having the 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 the text between Client
and P.\d
.I am trying the regex, Regex
我想要客户端和P. \ d之间的文本。我正在尝试正则表达式,正则表达式
(P.\d)[\s\S]*(?=^.+Client :?)
But it matching from the first Page P.1
.I need the nearest P.\d
before Client. What should I change in my regex to match from P.4
.
但它匹配第一页P.1.I需要最近的P. \ d在客户之前。我应该如何改变我的正则表达式以匹配P.4。
1 个解决方案
#1
1
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:
我试过这个非贪婪的运算符,但这不会起作用。我试图摆脱整个正则表达式匹配你想要的,并使用组代替。然后你可以编写一个匹配器来匹配任何数量的P.1构造,并且它使得你最后的客户端字符串扫描更加简单,因为你不必尝试将它作为前瞻。从而:
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'.
似乎准确地产生了你想要的东西。语法(?
#1
1
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:
我试过这个非贪婪的运算符,但这不会起作用。我试图摆脱整个正则表达式匹配你想要的,并使用组代替。然后你可以编写一个匹配器来匹配任何数量的P.1构造,并且它使得你最后的客户端字符串扫描更加简单,因为你不必尝试将它作为前瞻。从而:
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'.
似乎准确地产生了你想要的东西。语法(?