正则表达式找到一个角色的位置

Leo*_*Leo -1 java regex

我必须在字符串中找到*的出现,并且基于字符串中*的位置,必须执行某些操作.

if(* found in the beginning of the String) {
 do this
}
if(* found in the middle of the String) {
 do this
}
if(* found at the end of the String) {
 do this
} 
Run Code Online (Sandbox Code Playgroud)

我使用了matcher.find()选项,但它没有给出所需的结果.

And*_*ner 7

用途String.indexOf:

int pos = str.indexOf('*');
if (pos == 0) {
  // Found at beginning.
} else if (pos == str.length() - 1) {
  // Found at end.
} else if (pos > 0) {
  // Found in middle.
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用startsWith/ endsWith/ contains:

if (str.startsWith('*')) {
  // Found at beginning.
} else if (str.endsWith('*')) {
  // Found at end.
} else if (str.contains('*')) {
  // Found in middle.
}
Run Code Online (Sandbox Code Playgroud)

这可能会略微提高效率,因为它避免了在结束时必须检查整个字符串*.但是,代码的可读性应该是在这两者之间进行选择的主要考虑因素,因为在许多情况下性能差异可以忽略不计.

当然,*如果您使用后一种方法,则无法获得实际位置.这取决于你真正想做的事情是否重要.