简体   繁体   中英

java - regex for string between two characters

How do I get the stuff in between two #? I have this

^(#(.+?)#)

and it returns a string

#blah blah blah#

but I only want

blah blah blah

How do I exclude the #?

您要查找的正则表达式为"#(.*?)# (请参见示例 )。

There are two groups in this regex. The first group (the outer parentheses) will give you "#blah blah blah#", and the second group will give you what you are looking for, "blah blah blah". You should access match.group(2) for the required result, where match is the matcher object.

The basic idea is to exclude the '#' characters from the capture group. The following will capture the text between the '#' but not the '#' characters themselves:

#(.*)#

Now, what if there are no characters between the '#'? If the string is ## , the above expression will capture an empty string. That might be what you want. But you might want the capture to fail instead. The following will do that:

#(.+)#    // Force the captured string to be non-empty

Now, what if the string might contain more than two '#'? For example, if the string is #a#b# , do you want it to capture a#b or a ? The previous regexes would capture the longer string. If you want the shorter, then either of the following should do that:

#(.*?)#       // Like your original example
#([^#]*)#     // capture only sequences of non-# characters

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