英文:
Regular expression to check for string between special characters in java
问题
我需要检查提供的字符串是否具有特定格式。格式如下:"这只是一个#<示例字符串>
用于测试。这个字符串必须具有这种#<特定格式>
"。
如果您看字符串,它包含特殊字符#<>
,以及在#<
和>
之间的一些字符串。我尝试了正则表达式:Pattern.compile("^[#<a-zA-Z0-9>]*$").matcher(string).find()
,但即使我没有在开头或结尾提供特殊字符,它也返回true。
我还尝试了一个if条件:if(string.matcher("#<"))
,但我认为这种方法不够好。我宁愿使用正则表达式。
我在这里做错了什么?
英文:
I have to check if the string provided has a specific format. The format is as follows: "This is just an #<example string>
just for test. This string has to be of this #<specific format>
".
If you look at the string, it has special characters #<>
with some string in between #<
and >
. I tried with regular expression: Pattern.compile("^[#<a-zA-Z0-9>]*$").matcher(string).find()
but it returns true even if I don't provide the special characters at the beginning or at the end.
I tried with an if condition too: if(string.matcher("#<"))
but I think this approach is lame. I'd rather go with the regular expresson.
What am I doing wrong here?
答案1
得分: 2
To match 1 or more "words" using the chars a-zA-Z0-9
between #<...>
and a whitespace boundary on the left and right, you could use
String regex = "(?<!\\S)#<[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*>(?!\\S)";
英文:
To match 1 or more "words" using the chars a-zA-Z0-9
between #<...>
and a whitespace boundary on the left and right, you could use
(?<!\S)#<[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*>(?!\S)
In Java
String regex = "(?<!\\S)#<[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*>(?!\\S)";
答案2
得分: 1
尝试:Pattern.compile("#<(.*?)>")
建议您使用类似 https://regex101.com/ 的网站来帮助您构建这些。
英文:
Try: Pattern.compile("#<(.*?)>")
Suggest you use a website like https://regex101.com/ to help you build these.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论