如何在java中匹配字符串和通配符

时间:2022-09-13 09:23:06

I need to write a regular expression that would match a string of value "*.log" I have the following code and its doesnt seem to work as expected.

我需要编写一个正则表达式,它匹配一个值“* .log”的字符串我有以下代码,它似乎没有按预期工作。

if (name.matches("\\*\\.log")

The above statement returns false, when the value of name is "*.log"

当name的值为“* .log”时,上面的语句返回false

Any help is much appreciated.

任何帮助深表感谢。

4 个解决方案

#1


Why are you doing that? Couldn't you just do

你为什么这样做?你不能这样做吗?

if(name.endsWith(".log"))

It seems to me like that would be a simpler option, since anything can be before .log, just like if you used a wildcard.
Also, if you want to make sure that it isn't just ".log", that is also very simple.

在我看来,这将是一个更简单的选项,因为任何事情都可以在.log之前,就像你使用通配符一样。另外,如果你想确保它不仅仅是“.log”,那也很简单。

if(name.endsWith(".log") && !name.equals(".log"))

Hopefully I helped a bit!

希望我帮了一下!

#2


I think this regular expression will helpful to you......

我认为这个正则表达式对你有帮助......

^\*\.log$

For php,

$re = "/\\*\\.log/"; 
$str = "*.log"; 

preg_match($re, $str, $matches);

For JavaScript,

var re = /\*\.log/; 
var str = '*.log';
var m;

if ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

For Python,

import re
p = re.compile(ur'\*\.log')
test_str = u"*.log"

re.search(p, test_str)

#3


You can use this code :

您可以使用此代码:

String name="test.log";
if (name.matches("^.+\\.log$") ) {
    System.out.println("Okay");
}

#4


As simple as:

很简单:

\*\.log

You can always check here:

你可以随时查看:

https://www.regex101.com/r/vK7mQ6/2

#1


Why are you doing that? Couldn't you just do

你为什么这样做?你不能这样做吗?

if(name.endsWith(".log"))

It seems to me like that would be a simpler option, since anything can be before .log, just like if you used a wildcard.
Also, if you want to make sure that it isn't just ".log", that is also very simple.

在我看来,这将是一个更简单的选项,因为任何事情都可以在.log之前,就像你使用通配符一样。另外,如果你想确保它不仅仅是“.log”,那也很简单。

if(name.endsWith(".log") && !name.equals(".log"))

Hopefully I helped a bit!

希望我帮了一下!

#2


I think this regular expression will helpful to you......

我认为这个正则表达式对你有帮助......

^\*\.log$

For php,

$re = "/\\*\\.log/"; 
$str = "*.log"; 

preg_match($re, $str, $matches);

For JavaScript,

var re = /\*\.log/; 
var str = '*.log';
var m;

if ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

For Python,

import re
p = re.compile(ur'\*\.log')
test_str = u"*.log"

re.search(p, test_str)

#3


You can use this code :

您可以使用此代码:

String name="test.log";
if (name.matches("^.+\\.log$") ) {
    System.out.println("Okay");
}

#4


As simple as:

很简单:

\*\.log

You can always check here:

你可以随时查看:

https://www.regex101.com/r/vK7mQ6/2