简体   繁体   中英

What regex trims arbitrary punctuation from the start and end of a string in Javascript?

I have an input line that accepts a string of arbitrary length containing two entities: an identifier type from a small list, and an identifier that can contain letters, numbers, and punctuation. The two entities are separated by punctuation that might be, but is not limited to: | : / \\ , | : / \\ ,

I have some code that finds the identifier type in the supplied string:

 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]; } } 

However, this does not capture the punctuation serving as separators:

if

rawinput = "T14 11/15/11 | WPK |"

then

inputContents == "T14 11/15/11 | |"

whereas I would like

inputContents == "T14 11/15/11"

Is there a regex that will strip out all leading or trailing punctuation and white space, but will preserve the punctuation in the middle?

(.+?)\\s+[^a-zA-Z0-9]+.*$

You can see its test at: https://regex101.com/r/stDlXi/1

If you wish to specifically look for punctuation marks, then this will also do: (.+?)\\s+[\\|\\\\/\\?!\\.,;:-]+.*$ . I have omitted brackets, guillemets, ellipsis, apostrophe, quotation marks etc. If you need to consider them you can include them inside the square brackets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM