正则表达式来检查Java中特殊字符之间的字符串

huangapple go评论71阅读模式
英文:

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)";

Regex demo

英文:

To match 1 or more "words" using the chars a-zA-Z0-9 between #&lt;...&gt; and a whitespace boundary on the left and right, you could use

(?&lt;!\S)#&lt;[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*&gt;(?!\S)

In Java

String regex = &quot;(?&lt;!\\S)#&lt;[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*&gt;(?!\\S)&quot;;

Regex demo

答案2

得分: 1

尝试:Pattern.compile("#<(.*?)>")

建议您使用类似 https://regex101.com/ 的网站来帮助您构建这些。

英文:

Try: Pattern.compile(&quot;#&lt;(.*?)&gt;&quot;)

Suggest you use a website like https://regex101.com/ to help you build these.

huangapple
  • 本文由 发表于 2020年8月6日 21:51:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63285074.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定