简体   繁体   English

如何用零字符正则表达式检查Java中的字符串?

[英]How to Check a String in Java with an Zero Character RegEx?

The following piece of code checks for same variable portion /en(^$|.*) which is empty or any characters. 以下代码检查相同的变量部分/en(^$|.*)是否为空或任何字符。 So the expression should match /en AND /en/bla , /en/blue etc. But the expression doesn't work when checking for just /en . 因此该表达式应与/en AND /en/bla/en/blue等匹配。但是仅检查/en时该表达式不起作用。

"/en".matches("/en(^$|.*)")

Is there a way to make this empty regex check (^$) perform with java? 有没有办法使此空的正则表达式检查(^ $)与Java一起执行?

edit 编辑

I mean: Is there a way to make this piece of code return true ? 我的意思是:有没有办法使这段代码返回true

What you're currently doing is checking whether en is followed by the start of string then the end of string (which doesn't make sense, since the start of string needs to be first) or anything else. 您当前正在执行的操作是检查是否在en后面跟随字符串的开头,然后是字符串的结尾(这没有意义,因为字符串的开头必须在第一个),或者其他任何方法。 This should work: 这应该工作:

"/en".matches("/en(|.*)")

Or just using ? 还是只是使用? (optional): (可选的):

"/en".matches("/en(.*)?")

But it's rather pointless, since * is zero or more (so a blank string will match for .* ), just this should do it: 但这是毫无意义的,因为*为零或更大(因此,空白字符串将与.*匹配),只需这样做即可:

"/en".matches("/en.*")

EDIT: 编辑:

Your code was already returning true, but it was not matching the ^$ part, but rather .* (similar to the above). 您的代码已经返回true,但是它与^$部分不匹配,而与.*相匹配(类似于上面的内容)。

I should point out that you may as well use startsWith , unless your real data is more complex: 我应该指出,除非您的实际数据更为复杂,否则您也可以使用startsWith

"/en".startsWith("/en")

Is there a way to make this piece of code return true? 有没有办法使这段代码返回true?

 "/en".matches("/en(^$|.*)") 

That code does return true. 该代码确实返回true。 Just try it! 去尝试一下!

However, your pattern is unnecessarily complex. 但是,您的模式不必要地复杂。 Try: 尝试:

"/en".matches("/en.*")

This will match /en followed by anything (including nothing). 这将匹配/en后跟任何内容(包括不包含任何内容)。

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

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