Java 正则表达式匹配词
Java Regex matching word
我有一个文件正在通读和搜索单词。
姓名 = 杰克
主动多普勒名称 = 200ms
正在使用
搜索即时消息
if(line.contains("name")
这条语句找到了两行,但我只需要它找到第一行,因为我有一个单独的语句来罚款 "active Doppler name"。所以我需要正则表达式方面的帮助来检查它是否只是单词 "name" 之前的空格。这些是我想出的几个选项,但不起作用
if(line.contains("\s+\bname")
或
if(line.contains("^\s+name")
谢谢
String.contains
不将正则表达式作为参数。
您可以使用:
// matches the whole line:
// ┌ start of input
// | ┌ any or no whitespace (as your original pattern suggests)
// | | ┌ literal "name"
// | | | ┌ any other character sequence to follow, or no characters
line.matches("^\s*name.*");
备注
如果你想对此进行改进,你可以声明一个常量Pattern
,并匹配/反向引用每一行。
例如:
// similar as before, but captures the value for "name"
// and validates with "=characters" after it
static final Pattern NAME_VALUE = Pattern.compile("^\s*name\s*=\s*(.+)");
// ...
Matcher m = NAME_VALUE.matcher(line);
if (m.find()) {
// "jake"
String myValue = m.group(1);
}
如果 "name" 始终是您行中的第一个单词,您可以匹配 /^ *(name)/
我有一个文件正在通读和搜索单词。
姓名 = 杰克
主动多普勒名称 = 200ms
正在使用
搜索即时消息if(line.contains("name")
这条语句找到了两行,但我只需要它找到第一行,因为我有一个单独的语句来罚款 "active Doppler name"。所以我需要正则表达式方面的帮助来检查它是否只是单词 "name" 之前的空格。这些是我想出的几个选项,但不起作用
if(line.contains("\s+\bname")
或
if(line.contains("^\s+name")
谢谢
String.contains
不将正则表达式作为参数。
您可以使用:
// matches the whole line:
// ┌ start of input
// | ┌ any or no whitespace (as your original pattern suggests)
// | | ┌ literal "name"
// | | | ┌ any other character sequence to follow, or no characters
line.matches("^\s*name.*");
备注
如果你想对此进行改进,你可以声明一个常量Pattern
,并匹配/反向引用每一行。
例如:
// similar as before, but captures the value for "name"
// and validates with "=characters" after it
static final Pattern NAME_VALUE = Pattern.compile("^\s*name\s*=\s*(.+)");
// ...
Matcher m = NAME_VALUE.matcher(line);
if (m.find()) {
// "jake"
String myValue = m.group(1);
}
如果 "name" 始终是您行中的第一个单词,您可以匹配 /^ *(name)/