![](/img/trans.png)
[英]JavaScript: Regex - Cannot start/end with punctuation, no repeating punctuation
[英]What regex trims arbitrary punctuation from the start and end of a string in Javascript?
我有一條輸入線,它接受包含兩個實體的任意長度的字符串:一個小列表中的標識符類型,以及一個可以包含字母,數字和標點符號的標識符。 這兩個實體是由標點符號可能是分離的,但不限於: | : / \\ ,
| : / \\ ,
我有一些代碼可在提供的字符串中找到標識符類型:
for(var i = 0; i < idTypes.length; i++){ var search = rawInput.toUpperCase().search(idTypes[i]); if (search >= 0){ var inputType = idTypes[i]; var regEx = new RegExp(inputType, "i") var inputContents = rawInput.replace(regEx,""); console.log("This is type " + inputType + " with contents " + inputContents); return [inputType,inputContents]; } }
但是,這不會捕獲用作分隔符的標點符號:
如果
rawinput = "T14 11/15/11 | WPK |"
然后
inputContents == "T14 11/15/11 | |"
而我想
inputContents == "T14 11/15/11"
是否有一個正則表達式會刪除所有前導或尾隨的標點符號和空格,但會保留中間的標點符號?
(.+?)\\s+[^a-zA-Z0-9]+.*$
您可以在以下位置查看其測試: https : //regex101.com/r/stDlXi/1
如果您希望專門查找標點符號,則也可以這樣做: (.+?)\\s+[\\|\\\\/\\?!\\.,;:-]+.*$
。 我省略了方括號,guillemet,省略號,撇號,引號等。如果需要考慮它們,可以將其包括在方括號內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.