Remove specific character if at the beginning of a string or consecutive at any place in a string

前端 未结 2 875
囚心锁ツ
囚心锁ツ 2021-01-25 05:17

I\'m currently trying to make a regex to remove every of those character [0-9] \\ - * \\\' if they are either at the beginning of the string, end of the string or if they are co

相关标签:
2条回答
  • 2021-01-25 05:55

    You may use

    ^[^a-zA-Z]+|[^a-zA-Z]+$|(['* -])['* -]+|[^a-zA-Z'* -]
    

    Replace with the backreference to Group 1 value, $1:

    s.replace(/^[^a-zA-Z]+|[^a-zA-Z]+$|(['* -])['* -]+|[^a-zA-Z'* -]/g, '$1')
    

    See the regex demo

    Details

    • ^[^a-zA-Z]+ - one or more chars other than ASCII letters at the start of the string
    • | - or
    • [^a-zA-Z]+$ - one or more chars other than ASCII letters at the end of the string
    • | - or
    • (['* -])['* -]+ - a ', *, space or - captured into Group 1 and then 1+ or more of such chars
    • | - or
    • [^a-zA-Z'* -] - a char other than ASCII letter, ', *, space or -.
    0 讨论(0)
  • 2021-01-25 06:13

    You might use an alternation and a character class listing all the characters that you want to remove at the start of the string, the end or repeated 2 or more times using {2,}

    ^[ *'0-9?&_$-]+|[ *'0-9?&_$-]+$|[ *'0-9?&_$-]{2,}
    

    Regex demo

    If you want to remove all except characters a-zA-Z and a negated character class to match any character not in the character class

    In the replacement use an empty string.

    ^[^a-zA-Z]+|[^a-zA-Z]+$|[^a-zA-Z]{2,}
    

    Regex demo

    0 讨论(0)
提交回复
热议问题