[英]Splitting a String at the beginning of a line
I have a text that i want to split whenever i encounter "WORD" at the beginning of a line and with no characters following it. 我有一个文本,只要我在一行的开头遇到“ WORD”且后面没有字符,就想拆分。 I used text.split("WORD"), only its not good because for example %hi hi WORD should not be matched by the split method, and right now it is matched.
我使用了text.split(“ WORD”),只是它不好,因为例如%hi hi WORD不应由split方法匹配,并且现在已经匹配了。 i tried using "^WORD" but that only matches WORD at the beginning of the entire text.
我尝试使用“ ^ WORD”,但只匹配整个文本开头的WORD。
any ideas how do i do that? 任何想法我该怎么做? btw i use java if that matters
顺便说一句,如果重要的话,我会使用Java
Use the multiline modifier (which has the same effect as the Pattern.MULTILINE
flag for a regex pattern): 使用多行修饰符 (对于正则表达式模式,其作用与
Pattern.MULTILINE
标志相同):
text.split("(?m)^WORD");
It changes the meaning of ^
from "at the beginning of the string" to "at the beginning of a line" . 它将
^
的含义从“在字符串的开头”更改为“在行的开头” 。
As Tomalak posted, use the multiline modifier. 正如Tomalak发布的那样,使用多行修饰符。 If you want to keep the WORD itself you could also do:
如果您想保留WORD本身,也可以执行以下操作:
Pattern p = Pattern.compile("(^WORD .*$)", Pattern.MULTILINE);
String input = "WORD something. And WORD not at beginning.\nWORD something.";
Matcher m = p.matcher(input);
while (m.find()) {
System.out.println(m.group());
}
在一行的开头遇到“ WORD”,并且后面没有字符。
text.split("(?mis)^WORD(?!.)");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.