简体   繁体   English

正则表达式拆分驼峰案例

[英]Regex to split camel case

I have a regular expression in JavaScript to split my camel case string at the upper-case letters using the following code (which I subsequently got from here ):我在 JavaScript 中有一个正则表达式,可以使用以下代码(我随后从此处获得)在大写字母处拆分我的驼峰式大小写字符串:

"MyCamelCaseString"
    .replace(/([A-Z])/g, ' $1')
    .replace(/^./, function(str){ return str.toUpperCase(); })

Thus that returns:因此返回:

"My Camel Case String"

Which is good.哪个好。 However, I want to step this up a notch.但是,我想更上一层楼。 Could someone help me with a regex which will split if, and only if, the former character is lower-case and the latter is upper-case.有人可以帮助我使用正则表达式,当且仅当前一个字符为小写而后者为大写时,它才会拆分。

Thus, the above example will be the result I expect, but if I do:因此,上面的例子将是我期望的结果,但如果我这样做:

"ExampleID"

Then I get returned:然后我得到了回报:

"Example ID"

Instead of代替

"Example I D"

Since it's splitting at each upper-case and ignoring anything before it.因为它在每个大写字母处拆分并忽略它之前的任何内容。

Hope that makes sense!希望这是有道理的! And thanks :).并感谢:)。

My guess is replacing /([AZ])/ with /([az])([AZ])/ and ' $1' with '$1 $2'我的猜测是将/([AZ])/替换为/([az])([AZ])/并将' $1'替换为'$1 $2'

"MyCamelCaseString"
    .replace(/([a-z])([A-Z])/g, '$1 $2');

/([a-z0-9])([AZ])/ for numbers counting as lowercase characters /([a-z0-9])([AZ])/对于算作小写字符的数字

 console.log("MyCamelCaseStringID".replace(/([a-z0-9])([AZ])/g, '$1 $2'))

"MyCamelCaseString".replace(/([a-z](?=[A-Z]))/g, '$1 ')

输出:

"My Camel Case String"

If you want an array of lower case words:如果您想要一组小写单词:

"myCamelCaseString".split(/(?=[A-Z])/).map(s => s.toLowerCase());

If you want a string of lower case words:如果你想要一串小写单词:

"myCamelCaseString".split(/(?=[A-Z])/).map(s => s.toLowerCase()).join(' ');

If you want to separate the words but keep the casing:如果要分隔单词但保留大小写:

"myCamelCaseString".replace(/([a-z])([A-Z])/g, '$1 $2')

Sometime camelCase strings include abbreviations, for example:有时,camelCase 字符串包含缩写,例如:

PDFSplitAndMergeSamples
PDFExtractorSDKSamples
PDFRendererSDKSamples
BarcodeReaderSDKSamples

And in this case the following function will work, it splits the string leaving abbreviations as separate strings:在这种情况下,以下函数将起作用,它将字符串拆分为单独的字符串:

function SplitCamelCaseWithAbbreviations(s){
   return s.split(/([A-Z][a-z]+)/).filter(function(e){return e});
}

Example:例子:

 function SplitCamelCaseWithAbbreviations(s){ return s.split(/([AZ][az]+)/).filter(function(e){return e}); } console.log(SplitCamelCaseWithAbbreviations('PDFSplitAndMergeSamples')); console.log(SplitCamelCaseWithAbbreviations('PDFExtractorSDKSamples')); console.log(SplitCamelCaseWithAbbreviations('PDFRendererSDKSamples')); console.log(SplitCamelCaseWithAbbreviations('BarcodeReaderSDKSamples'));

I found that none of the answers for this question really worked in all cases and also not at all for unicode strings, so here's one that does everything, including dash and underscore notation splitting.我发现这个问题的所有答案都没有真正适用于所有情况,也不适用于 unicode 字符串,所以这里有一个可以做所有事情的答案,包括破折号和下划线符号拆分。

 let samples = [ "ThereIsWay_too MuchCGIInFilms These-days", "UnicodeCanBeCAPITALISEDTooYouKnow", "CAPITALLetters at the StartOfAString_work_too", "As_they_DoAtTheEND", "BitteWerfenSie-dieFußballeInDenMüll", "IchHabeUberGesagtNichtÜber", "2BeOrNot2Be", "ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad" ]; samples.forEach(sample => console.log(sample.replace(/([^[\\p{L}\\d]+|(?<=[\\p{Ll}\\d])(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}[\\p{Ll}\\d])|(?<=[\\p{L}\\d])(?=\\p{Lu}[\\p{Ll}\\d]))/gu, '-').toUpperCase()));

If you don't want numbers treated as lower case letters, then:如果您不想将数字视为小写字母,则:

 let samples = [ "2beOrNot2Be", "ICannotBelieveThe100GotRenewed. It-isSOOOOOOBad" ]; samples.forEach(sample => console.log(sample.replace(/([^\\p{L}\\d]+|(?<=\\p{L})(?=\\d)|(?<=\\d)(?=\\p{L})|(?<=[\\p{Ll}\\d])(?=\\p{Lu})|(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})|(?<=[\\p{L}\\d])(?=\\p{Lu}\\p{Ll}))/gu, '-').toUpperCase()));

也可以使用正则表达式非单词边界\\B字符

 console.log("MyCamelCaseString".replace(/(\\B[AZ])/g, ' $1'));

Hi I saw no live demo , thanks @michiel-dral嗨,我没有看到现场演示,谢谢@michiel-dral

 var tests =[ "camelCase", "simple", "number1Case2"] function getCamelCaseArray(camel) { var reg = /([a-z0-9])([AZ])/g; return camel.replace(reg, '$1 $2').split(' '); } function printTest(test) { document.write('<p>'+test + '=' + getCamelCaseArray(test)+'</p>'); } tests.forEach(printTest);
 <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body> </body> </html>

I prefer to work with arrays over strings.我更喜欢使用数组而不是字符串。 It's easier to debug and more flexible.调试更容易,更灵活。 This is an actual join instead of replace .这是一个实际的join而不是replace I haven't dealt with white spaces in the strings but you could just trim each element easily enough.我还没有处理字符串中的空格,但您可以轻松地修剪每个元素。

 const splitCamelCase = str => str.match(/^[AZ]?[^AZ]*|[AZ][^AZ]*/g).join(' '); console.log(splitCamelCase('fooMyCamelCaseString')); console.log(splitCamelCase('MyCamelCaseString')); console.log(splitCamelCase('XYZMyCamelCaseString')); console.log(splitCamelCase('alllowercase'));

If you're like me and had a camelCase value such as:如果你像我一样有一个camelCase值,例如:

thisIsMyCamelCaseValue where the first letter is lowercased thisIsMyCamelCaseValue其中第一个字母是小写的

function fromCamelCase(value) {
    const spaced = value.replace(/([a-z])([A-Z])/g, '$1 $2');
    return spaced.charAt(0).toUpperCase() + spaced.slice(1);
}

You can use a combination of regEx , replace , and trim .您可以组合使用regExreplacetrim

"ABCMyCamelCaseSTR".replace(/([A-Z][a-z0-9]+)/g, ' $1 ')
                   .replace(/\s{2}/g," ").trim()

// ABC My Camel Case STR
a = 'threeBlindMice'
a.match(/[A-Z]?[a-z]+/g) // [ 'three', 'Blind', 'Mice' ]

is the simplest way I've found, for simple camel/titlecase splitting.是我发现的最简单的方法,用于简单的骆驼/标题分割。

If you want to capitalize and add space between numbers as well, this works.如果您还想大写并在数字之间添加空格,这很有效。

const str = 'this1IsASampleText';
str.charAt(0).toUpperCase() + value.slice(1); // Capitalize the first letter
str.replace(/([0-9A-Z])/g, ' $&'); // Add space between camel casing

Results:结果:

This 1 Is A Sample Text    

I recently came across this question and needed to do the exact same thing:我最近遇到了这个问题,需要做同样的事情:

employeeID should be rendered as Employee ID员工ID应呈现为员工 ID

I found this convert case library from zellwk plus a little additional reduce function did the trick for me:我发现zellwk 的这个 转换案例库加上一些额外的 reduce 函数对我有用:

import { toTitle } from "./convert-case.js";

// NB. Assumes sequential single chars can be concatenated
// ex. N B A Finals => NBA Finals
const reducer = (total, currentValue, currentIndex, arr) => {
  if (
    currentValue.length === 1 &&
    !(currentIndex > 0 && arr[currentIndex - 1].length > 1)
  ) {
    return total + currentValue;
  } else {
    return total + " " + currentValue;
  }
};

const concatSingleChars = (title) => {
  const arrTitle = title.split(" ");
  return arrTitle.reduce(reducer);
};

const convertCase = (str) => {
  const s = toTitle(str);
  return concatSingleChars(s);
};

const tests = [
  "colName",
  "This_Is_A_title",
  "And_How_About_thisOne",
  "MaryHadALittleLamb",
  "employeeID",
  "N B A Finals",
  "N B A Finals in L A",
  "I Love L A"
];

const titles = tests.map((test) => {
  return convertCase(test);
});

console.log(titles);

这个正则表达式字符串是

.replace("/([a-zA-Z][a-z]*)/g",...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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