简体   繁体   English

Java Regex-在字符串中查找特定字符串

[英]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. 我试图匹配一个以设置的单词“ hotel”开头的字符串,然后是一个连字符,然后是任意长度的单词,然后是另一个连字符,最后是任意长度的数字。

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: 进一步编辑:详细说明Dima的答案,添加捕获组以使检索输入的信息更加容易,并更正最后一位以仅接受数字:

^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/ . 尝试使用regex在线测试仪,例如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. 因此,如果您具有^hotel-\\b ,这将迫使hotel在字符串的开头。

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 \\b表示应该是单词边界

[^\\s-] means anything but - or whitespace [^\\s-]表示-或空格以外的任何内容

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

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

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