[英]regular expression in java for first three letters in a sentence
how to write an regular expression in java for the sentence that is similar below and that should match only first three characters of the sentence 如何在Java中为下面类似的句子写一个正则表达式,并且只应与句子的前三个字符匹配
ins(clear(icl>remove>do,plf>thing,obj>thing,ins>thing).@entry.@past,evidence(icl>indication>thing))
i tried this code but it also matches clear,evidence in the sentence.... 我尝试过此代码,但它也与句子中的清晰证据相匹配。
String pattern2="[-a-z0-9R:._-`&=*'`~\"\\+[\\s]]+[\\(]";
Pattern r2 = Pattern.compile(pattern2);
Matcher m2 = r2.matcher(line);
while (m2.find())
{
rel = m2.group();
rel = rel.substring(0, rel.length()-1).trim();
System.out.println("The relation are " + rel);
}
I guess you should remove firstly all non-letters 我想你应该先删除所有非字母
String result = string.replaceAll("[^a-zA-Z]", "");
And then just taking first three symbols : 然后只取前三个符号:
result.substring(0, 3)
If you want to only get match from start of the line you can add ^
at start of your regex (before [
). 如果只想从行首开始匹配,可以在正则表达式的开头(在
[
]之前)添加^
。
If you want to be sure that matched part before (
will have 3 characters don't use ..]+
but ..]{3}
. 如果要确保之前匹配的部分
(
将有3个字符,请不要使用..]+
而是..]{3}
。
Also if you want to just check if some characters are after interesting part but you don't want to include them use look-ahead mechanism (?=...)
like in your case (?=[\\\\(])
or simpler (?=[(])
- there is no need to escape (
with \\\\
and []
at the same time. 另外,如果您只想检查某些字符是否位于有趣的部分之后,但又不想包含它们,则可以使用前瞻性机制
(?=...)
例如您的情况(?=[\\\\(])
或更简单(?=[(])
-不需要转义(
使用\\\\
和[]
。
So maybe change your pattern to 因此,也许将模式更改为
String pattern2 = "^[-a-z0-9R:._-`&=*'`~\"+\\s]{3}(?=[(])";
Also I am not sure if _-`
is what you mean since it will create range of characters between _
and `
我也不确定
_-`
是否代表您的意思,因为它会在_
和`
之间创建字符范围
此正则表达式匹配前三个字符:
^...
这个...
String pattern2="^[^\\(]+";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.