I have JTextPane which colors "int" words blue. Such regexp is wrong because it will also color "print":
我有JTextPane,其中“int”字为蓝色。这样的正则表达式是错误的,因为它也会着色“打印”:
int + "(\\[\\])*" //To match eg. int[]
So I came on idea with such regexp:
所以我想到了这样的正则表达式:
"\\s" + int + "(\\[\\])*"
Its okay but doesnt work if user types int as first in text pane. How to solve this problem? Is there some symbol for NOTHING? So i could make: \s | NOTHING
没关系,但如果用户在文本窗格中将int作为第一个键入,则无效。如何解决这个问题呢?没有一些符号吗?所以我可以做:\ s |没有
3 个解决方案
#1
5
Just match int
surrounded by word boundaries, which are matched by \b
. The pattern:
只需匹配由字边界包围的int,它与\ b匹配。模式:
"\\bint\\b"
More reading over at the always-excellent regular-expressions.info.
更多阅读总是优秀的regular-expressions.info。
#2
1
Do you want an optional space? That would be \\s?
. Or to allow zero or more spaces: \\s*
.
你想要一个可选的空间吗?那会是\\ s?或者允许零个或多个空格:\\ s *。
#3
1
I recommend using this:
我建议使用这个:
/\bint\S*/ig
Not entirely sure how that translates to Java, but the string portion would look like this:
不完全确定如何转换为Java,但字符串部分将如下所示:
"\\bint\\S*"
The regex translates to:
正则表达式转换为:
find "int" following a word boundary, capture it and anything else until a whitespace character.
在单词边界后面找到“int”,捕获它和其他任何东西直到空白字符。
It allows you to match
它可以让你匹配
int[]
int()
interesting
int!@#$%^&*()_+~=-
etc etc.
If you want to ONLY capture int[], int()
and the like, the regex would obviously be different.
如果你只想捕获int [],int()等,那么正则表达式显然会有所不同。
#1
5
Just match int
surrounded by word boundaries, which are matched by \b
. The pattern:
只需匹配由字边界包围的int,它与\ b匹配。模式:
"\\bint\\b"
More reading over at the always-excellent regular-expressions.info.
更多阅读总是优秀的regular-expressions.info。
#2
1
Do you want an optional space? That would be \\s?
. Or to allow zero or more spaces: \\s*
.
你想要一个可选的空间吗?那会是\\ s?或者允许零个或多个空格:\\ s *。
#3
1
I recommend using this:
我建议使用这个:
/\bint\S*/ig
Not entirely sure how that translates to Java, but the string portion would look like this:
不完全确定如何转换为Java,但字符串部分将如下所示:
"\\bint\\S*"
The regex translates to:
正则表达式转换为:
find "int" following a word boundary, capture it and anything else until a whitespace character.
在单词边界后面找到“int”,捕获它和其他任何东西直到空白字符。
It allows you to match
它可以让你匹配
int[]
int()
interesting
int!@#$%^&*()_+~=-
etc etc.
If you want to ONLY capture int[], int()
and the like, the regex would obviously be different.
如果你只想捕获int [],int()等,那么正则表达式显然会有所不同。