簡體   English   中英

使用正則表達式捕獲/包含並在之后選擇字符

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

我有正則表達式

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

我正在嘗試捕獲/(含)之后的所有內容,直到#或? (獨家)。

我嘗試過正則表達式的字符串:

/hello.there#test正確地給了我/hello.there

但是,僅對/進行嘗試不會對任何內容進行分組。 它也不會在字符串/ h中分組任何內容。 我認為可以做到這一點,因為我在要捕獲的場景中加入了z。

如何改進正則表達式,以便在排除#和之后捕獲/(包括)和所有內容? 而忽略#和?之后的任何內容

謝謝

當您需要匹配某些字符而不是其他字符時,您應該考慮否定的字符類

匹配除#?任何字符? 使用[^#?] 要匹配零個或多個出現,請在其后添加* 采用

/([^#?]*)

正則表達式演示

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
}

如果要在#?之后忽略字符? ,然后直接排除那些。

(/[^#?]*)

在此正則表達式中, /在組中,因此您可以捕獲它,並且[^#?]包括除#?之外的所有字符? (當然,這些字符之后的任何字符都將被忽略)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM