Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java模式接受带空格的字符串_Java_Regex_Pattern Matching - Fatal编程技术网

java模式接受带空格的字符串

java模式接受带空格的字符串,java,regex,pattern-matching,Java,Regex,Pattern Matching,我正在尝试使用模式和匹配器在关键字前后添加字符串。我现在有这个代码 Pattern p = Pattern.compile("([\\w.]+)\\W+=\\W+([\\w.]+)"); Matcher m = p.matcher("something = 1.21 and another = 2 && something else == 123?"); while (m.find()) System.out.printf(

我正在尝试使用模式和匹配器在关键字前后添加字符串。我现在有这个代码

Pattern p = Pattern.compile("([\\w.]+)\\W+=\\W+([\\w.]+)");
        Matcher m = p.matcher("something = 1.21 and another = 2 && something else == 123?");
        while (m.find())
            System.out.printf("'%s', '%s'%n", m.group(1), m.group(2));
输出:

我试图只传入“=”而不是“=”,因为我不希望“=”出现在列表中

无论何时我尝试这个,都不会打印出任何内容

期望输出:


我认为当前模式的问题在于
\W+
匹配空格和任何其他非单词字符,包括
=
。这会导致
==
术语的错误匹配。我建议只使用
\s*
来表示变量名/值和符号之间的分隔符。以下是脚本的稍微更新版本:

Pattern p = Pattern.compile("([\\w.]+)\\s*=\\s+([\\w.]+)");
Matcher m = p.matcher("something = 1.21 and another = 2 && something else == 123?");
while (m.find()) {
    System.out.printf("'%s', '%s'%n", m.group(1), m.group(2));
}
这将产生:

'something', '1.21'
'another', '2'

我认为当前模式的问题在于
\W+
匹配空格和任何其他非单词字符,包括
=
。这会导致
==
术语的错误匹配。我建议只使用
\s*
来表示变量名/值和符号之间的分隔符。以下是脚本的稍微更新版本:

Pattern p = Pattern.compile("([\\w.]+)\\s*=\\s+([\\w.]+)");
Matcher m = p.matcher("something = 1.21 and another = 2 && something else == 123?");
while (m.find()) {
    System.out.printf("'%s', '%s'%n", m.group(1), m.group(2));
}
这将产生:

'something', '1.21'
'another', '2'

我知道s的意思,我读过手册。s是一个空白字符,是[\t\n\x0b\r\f]的缩写,但不知道在它旁边添加*和+时意味着什么。我尽量灵活,并假设在
=
和LHS\RHS之间可能没有任何空白。最后一个问题:如果输入是something=something(),我如何实现它;我希望输出包含();部分?一般模式
\S+\S*=\S*\S+
可能会起作用。它不起作用:/我像你说的那样尝试了这个模式。编译(([\\w.]+)\\S+\\S*=\\S*\\S+([\\w.]+));我知道s的意思,我读过手册。s是一个空白字符,是[\t\n\x0b\r\f]的缩写,但不知道在它旁边添加*和+时意味着什么。我尽量灵活,并假设在
=
和LHS\RHS之间可能没有任何空白。最后一个问题:如果输入是something=something(),我如何实现它;我希望输出包含();部分?一般模式
\S+\S*=\S*\S+
可能会起作用。它不起作用:/我像你说的那样尝试了这个模式。编译(([\\w.]+)\\S+\\S*=\\S*\\S+([\\w.]+));