简体   繁体   中英

Java Regex - Finding specific string within a String

I am trying to match a string that start with the set word "hotel", then a hyphen, then a word of any length, then another hyphen and finally a number of any length.

Edit: Dima gave the solution I needed in the comments of this question! Thanks Dima.

Further edit: elaborating on Dima's answer, adding capturing groups making it easier to retrieve the information entered, and correcting the last bit to only accept digits:

^hotel-(.+)-(\\d+)

^hotel-(.)*$

(But hotel-something WILL work, according to your initial statement).

So, if you actually want something like:

hotel-XXXXXX-YYYYYYY

Then the regex is :

^hotel-(.)*-(.)*$

Try a regex online tester like http://www.regextester.com/ .

If you want to match the start of the input, you use ^ .

so if you have ^hotel-\\b , that will force hotel to be at the start of the string.

as a note, you can use $ for the end of the string in a similar way.

\bhotel-[^\s-]+-[^\s-]+\b

\\b means that it should be a word boundery

[^\\s-] means anything but - or whitespace

https://regex101.com/r/mH3vY8/1

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