简体   繁体   English

使用正则表达式捕获/包含并在之后选择字符

[英]using regex to capture / inclusive and select characters after

I have the regular expression 我有正则表达式

[/].([a-z/!@$%^&*()-+><~*\.]+)

which I am trying to capture everything after the / (inclusive) up to a # or ? 我正在尝试捕获/(含)之后的所有内容,直到#或? (exclusive). (独家)。

The strings I have tried the regex on: 我尝试过正则表达式的字符串:

/hello.there#test properly gives me the /hello.there /hello.there#test正确地给了我/hello.there

however trying it on just / does not group anything. 但是,仅对/进行尝试不会对任何内容进行分组。 It does not group anything in the string /h as well. 它也不会在字符串/ h中分组任何内容。 I thought it would do it for that because I included az in the set to capture. 我认为可以做到这一点,因为我在要捕获的场景中加入了z。

How can I improve the regex so that it captures / (inclusive) and everything after excluding # and ? 如何改进正则表达式,以便在排除#和之后捕获/(包括)和所有内容? while ignoring anything after # and ? 而忽略#和?之后的任何内容

Thank you 谢谢

When you need to match some chars other than some other characters, you should think of negated character classes . 当您需要匹配某些字符而不是其他字符时,您应该考虑否定的字符类

To match any char but # and ? 匹配除#?任何字符? use [^#?] . 使用[^#?] To match zero or more occurrences, add * after it. 要匹配零个或多个出现,请在其后添加* Use 采用

/([^#?]*)

See the regex demo 正则表达式演示

Java demo : Java演示

String str = "/hello.there#test";
Pattern ptrn = Pattern.compile("/([^#?]*)");
Matcher matcher = ptrn.matcher(str);
if (matcher.find()) {
    System.out.println(matcher.group());  // => /hello.there
    System.out.println(matcher.group(1)); // => hello.there
}

If you want to ignore characters after just # and ? 如果要在#?之后忽略字符? , then exclude those directly. ,然后直接排除那些。

(/[^#?]*)

In this regex, / is in the group so you can capture it, and [^#?] includes all characters except # and ? 在此正则表达式中, /在组中,因此您可以捕获它,并且[^#?]包括除#?之外的所有字符? .(of course, any characters after those will ignored) (当然,这些字符之后的任何字符都将被忽略)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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