JavaEar 专注于收集分享传播有价值的技术资料

Java regex to keep * only at the start or end

User would enter any String character, and the only allowed special character is * which can be placed either at the start or at the end of the string.

For example:

*hello*     -> *hello
*h*ello     -> *hello
h*llo*      -> hello*
hello**     -> hello*
**hell**o** -> *hello

I like to have a regex to do so.

2个回答

    最佳答案
  1. This one works somehow

    String s="*he**llo*";//anything
    boolean st=(s.startsWith("*"));
    boolean et=(s.endsWith("*"));
    String ns=s.replaceAll("\\*+","");
    ns=(st)?("*"+ns):(et)?(ns+"*"):ns;
    
  2. 参考答案2
  3. Below regex would match all the * which was not at the start or at the end. Just replace the matched * with a null value.

    Regex:

    (?<!^)\*(?!$)
    

    Java regex would be,

    "(?<!^)\\*(?!$)"
    

    Replacement string:

    Empty string
    

    DEMO

    Java code would be,

    String s="*he*****llo*";
    String out=s.replaceAll("(?<!^)\\*(?!$)","");
    System.out.println(out);
    

    IDEONE