简体   繁体   中英

Matching a pattern in Java when a few starting characters and a few ending characters are known

I would like to find a pattern which is a string. I know the first few characters of that string. And I also know the set of characters or words the string is ending with. How do I find this pattern? My string is constituted of words and special characters.

My string starts with a special character and ends with a special character followed by any two characters, which are variables.

If you don't know what the special character are and want to find them out from the input you can do

String regex = start + "(.*?)" + end + "(.)(.)"

As @olivier-grégoire points out, this assumes start and end are sufficiently quoted eg use Pattern.quote(String) if you are not sure.

The two characters matched will be in group 2 and 3 when you use a Matcher

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