78

我在 JavaScript 中有一个正则表达式,可以使用以下代码(我随后从这里得到)将我的驼峰式字符串拆分为大写字母:

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

因此返回:

"My Camel Case String"

哪个好。但是,我想把它提高一个档次。有人可以帮我一个正则表达式,当且仅当前一个字符是小写而后者是大写时才会拆分。

因此,上面的示例将是我期望的结果,但如果我这样做:

"ExampleID"

然后我被退回:

"Example ID"

代替

"Example I D"

因为它在每个大写字母处拆分并忽略它之前的任何内容。

希望这是有道理的!谢谢:)。

4

14 回答 14

146

我的猜测是/([A-Z])//([a-z])([A-Z])/' $1'替换'$1 $2'

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

/([a-z0-9])([A-Z])/对于计数为小写字符的数字

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

于 2013-08-22T11:39:47.100 回答
44
"MyCamelCaseString".replace(/([a-z](?=[A-Z]))/g, '$1 ')

输出:

"My Camel Case String"
于 2013-08-22T11:45:36.227 回答
26

如果你想要一个小写单词数组:

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

如果你想要一串小写单词:

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

如果要分隔单词但保留大小写:

"myCamelCaseString".replace(/([a-z])([A-Z])/g, '$1 $2')
于 2013-12-04T17:21:04.550 回答
17

有时 camelCase 字符串包含缩写,例如:

PDFSplitAndMergeSamples
PDFExtractorSDKSamples
PDFRendererSDKSamples
BarcodeReaderSDKSamples

在这种情况下,以下函数将起作用,它将字符串拆分为单独的字符串:

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

例子:

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

console.log(SplitCamelCaseWithAbbreviations('PDFSplitAndMergeSamples'));
console.log(SplitCamelCaseWithAbbreviations('PDFExtractorSDKSamples'));
console.log(SplitCamelCaseWithAbbreviations('PDFRendererSDKSamples'));
console.log(SplitCamelCaseWithAbbreviations('BarcodeReaderSDKSamples'));

于 2019-01-09T14:28:30.423 回答
5

我发现这个问题的答案在所有情况下都没有真正起作用,对于 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()));

如果您不希望将数字视为小写字母,则:

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()));

于 2020-06-23T04:03:06.790 回答
3

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

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

于 2020-04-21T12:58:10.013 回答
2

嗨,我没有看到现场演示,谢谢@michiel-dral

var tests =[ "camelCase",
             "simple",
             "number1Case2",
             "CamelCaseXYZ",
             "CamelCaseXYZa" 
           ]

function getCamelCaseArray(camel) {
  var reg = /([a-z0-9])([A-Z])/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>

于 2016-08-11T05:08:07.713 回答
1

如果您还想大写并在数字之间添加空格,则可以使用。

transform(value: string, ...args: any[]): string {
    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
}

结果:

This 1 Is A Sample Text    
于 2020-11-24T18:08:21.677 回答
1

如果你和我一样,并且有一个 camelCase 值,例如:

thisIsMyCamelCaseValue第一个字母小写的地方

function fromCamelCase(value) {
    const spaced = value.replace(/([a-z])([A-Z])/g, '$1 $2');
    return spaced.charAt(0).toUpperCase() + spaced.slice(1);
}
于 2021-03-25T14:04:15.557 回答
0
a = 'threeBlindMice'
a.match(/[A-Z]?[a-z]+/g) // [ 'three', 'Blind', 'Mice' ]

is the simplest way I've found, for simple camel/titlecase splitting.

于 2020-06-24T16:25:39.053 回答
0

您可以使用regExreplace和的组合trim

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

// ABC My Camel Case STR
于 2020-02-17T11:03:53.470 回答
0

我更喜欢使用数组而不是字符串。它更容易调试,更灵活。这是一个实际的join而不是replace. 我没有处理字符串中的空格,但您可以轻松地修剪每个元素。

const splitCamelCase = str => str.match(/^[A-Z]?[^A-Z]*|[A-Z][^A-Z]*/g).join(' ');

console.log(splitCamelCase('fooMyCamelCaseString'));
console.log(splitCamelCase('MyCamelCaseString'));
console.log(splitCamelCase('XYZMyCamelCaseString'));
console.log(splitCamelCase('alllowercase'));

于 2018-12-27T02:01:40.333 回答
0

我最近遇到了这个问题,需要做同样的事情:

employeeID应呈现为Employee ID

我发现这个来自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);
于 2021-03-22T01:05:06.940 回答
-4

这个正则表达式字符串是

.replace("/([a-zA-Z][a-z]*)/g",...);
于 2013-08-22T11:45:43.047 回答